我试图将JSON对象嵌套在HTTP请求的URL中以使用API。原始JSON是
{
"jsonrpc":"2.0",
"id":"12345",
"params":{
"api_key": "e983322o",
"preset_id": "12345678",
"user_id": "3265999"
},
"method":"Tags.get"
}
(这是经过测试并在REST客户端中运行)
Java中的方法是
private static void printSiteTags() {
try {
List<NameValuePair> params = new LinkedList<>();
params.add(new BasicNameValuePair("jsonrpc", "2.0"));
params.add(new BasicNameValuePair("id", "12345"));
params.add(new BasicNameValuePair("params[0]", new BasicNameValuePair("api_key", API_KEY).toString()));
params.add(new BasicNameValuePair("params[1]", new BasicNameValuePair("preset_id", "12345678").toString()));
params.add(new BasicNameValuePair("params[2]", new BasicNameValuePair("user_id", "3265999").toString()));
params.add(new BasicNameValuePair("method", "Tags.get"));
String rawUrl = addToUrl(SITE_URL, params);
//addToUrl just uses URLEncodedUtils
System.out.println(rawUrl);
URL url = new URL(rawUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoOutput(true);
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
for ( int c = in.read(); c != -1; c = in.read() )
System.out.print((char)c);
} catch (IOException e) {
e.printStackTrace();
}
}
原始网址的结果是
[base site]?jsonrpc=2.0&id=12345&%5Bparams%5D%5Bapi_key%5D=e983322o¶ms%5B1%5D=preset_id%3D12345678¶ms%5B2%5D=user_id%3D3265999&method=Tags.get
(这显然是错误的)
显然,服务器的响应是错误的。
答案 0 :(得分:0)
JSON应该进入请求BODY。 请求内容类型应该通过application / json。
如果你想继续使用URLConnection,那么看看这里例如: POST request send json data java HttpUrlConnection 但请注意,选择哪个库来格式化json正文并不重要,它只是一个文本 - 在你的情况下{“jsonrpc”:“2.0”,“id”:“12345”,...
还有其他方法,例如如果您使用httpClient,请参阅以下链接中的示例8: http://www.programcreek.com/java-api-examples/index.php?api=org.apache.commons.httpclient.methods.StringRequestEntity