反射-can';t从JSON-RPC请求调用java方法
我想从servlet调用一个基于JSON-RPC请求的方法,我有如下代码:反射-can';t从JSON-RPC请求调用java方法,java,servlets,reflection,json-rpc,Java,Servlets,Reflection,Json Rpc,我想从servlet调用一个基于JSON-RPC请求的方法,我有如下代码: public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); ServletInputStream in = request.getInputStr
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json");
ServletInputStream in = request.getInputStream();
PrintWriter out = response.getWriter();
String json_request = this.readStream(in);
Object id = null;
try {
JSONRPC2Request reqIn = JSONRPC2Request.parse(json_request);
id = reqIn.getID();
Object params = reqIn.getPositionalParams().toArray();
String method_name = reqIn.getMethod();
Service service = new Service();
Method[] methods = service.getClass().getMethods();
Method method = null;
// getMethod need class as second argument
for (int i=0; i<methods.length; ++i) {
if (methods[i].getName().equals(method_name)) {
method = methods[i];
break;
}
}
if (method != null) {
Object result = method.invoke(service, params);
JSONRPC2Response respOut = new JSONRPC2Response(result, id);
out.println(respOut);
} else {
out.println(JSONRPC2Error.METHOD_NOT_FOUND);
}
} catch (IllegalArgumentException e) {
out.println(new JSONRPC2Response(JSONRPC2Error.INVALID_PARAMS, id));
} catch (IllegalAccessException e) {
out.println(new JSONRPC2Response(JSONRPC2Error.INTERNAL_ERROR, id));
} catch (InvocationTargetException e) {
out.println(new JSONRPC2Response(JSONRPC2Error.INTERNAL_ERROR, id));
} catch (JSONRPC2ParseException e) {
out.println("{\"error\": \"Parse Error: " + e.getMessage() + "\"}");
}
}
我使用jQuery从javascript调用它:
var request = JSON.stringify({
method: "login",
params: ["foo", "Bar"],
id: 1,
jsonrpc: "2.0"
});
$.post('/app/rpc', request, function(res) { console.log(res); });
但我一直在得到运行时IllegalArgumentException。我的代码怎么了?我还尝试将参数强制转换为具有相同结果的对象。您确定参数是字符串数组而不是对象数组吗?@Johnbot现在我看到参数是
object
istead ofobject[]
。
var request = JSON.stringify({
method: "login",
params: ["foo", "Bar"],
id: 1,
jsonrpc: "2.0"
});
$.post('/app/rpc', request, function(res) { console.log(res); });