java 使用 JSON 对象作为有效负载向 REST API 发出 POST 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28889013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
POST request to REST API with JSON object as payload
提问by Prudhvi
I am trying to get the JSON response from the REST API using the POST request that has JSON payload (should be converted to URL encoded text before sending). I have followed some tutorials to implement the process but I get error with status code 400. I may not be encoding the given JSON string or missing something. Please help me solve this problem. Thanks.
我正在尝试使用具有 JSON 有效负载的 POST 请求从 REST API 获取 JSON 响应(应在发送前转换为 URL 编码文本)。我已经按照一些教程来实现这个过程,但我收到状态代码 400 的错误。我可能没有对给定的 JSON 字符串进行编码或遗漏了一些东西。请帮我解决这个问题。谢谢。
Here is my code
这是我的代码
try {
URL url = new URL("https://appem.totango.com/api/v1/search/accounts/health_dist");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("app-token", "1a1c626e8cdca0a80ae61b73ee0a1909941ab3d7mobile+testme@totango.com");
conn.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
conn.setRequestProperty("X-Requested-With","XMLHttpRequest");
String payload = "{\"terms\":[{\"type\":\"totango_user_scope\",\"is_one_of\":[\"[email protected]\"]}],\"group_fields\":[{\"type\":\"health\"}]}";
OutputStream os = conn.getOutputStream();
os.write(payload.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
采纳答案by Prudhvi
After following many posts and tutorials for more than 24 hours I got to know that I am not sending my URL parameters correctly. And also I learned that REST API call using ApacheHttpClientis comparatively easier. I resolved my HTTP error code 400 and got the response back from the server. Here is the working code for my issue.
在遵循许多帖子和教程超过 24 小时后,我知道我没有正确发送我的 URL 参数。而且我还了解到使用ApacheHttpClient调用 REST API相对更容易。我解决了我的 HTTP 错误代码 400 并从服务器得到了响应。这是我的问题的工作代码。
try {
httpClient = HttpClients.createDefault();
httpPost = new HttpPost("https://appem.totango.com/api/v1/search/accounts/health_dist");
List<NameValuePair> headers = new ArrayList<NameValuePair>(); //ArrayList to store header parameters
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); //ArrayList to store URL parameters
urlParameters.add(new BasicNameValuePair("query","{\"terms\":[{\"type\":\"totango_user_scope\",\"is_one_of\":[\"[email protected]\"]}],\"group_fields\":[{\"type\":\"health\"}]}"));
headers.add(new BasicNameValuePair("app-token", "1a1c626e8cdca0a80ae61b73ee0a1909941ab3d7mobile+testme@totango.com"));
headers.add(new BasicNameValuePair("Accept", "application/json, text/javascript, */*; q=0.01"));
headers.add(new BasicNameValuePair("X-Requested-With", "XMLHttpRequest"));
httpPost.setEntity(new UrlEncodedFormEntity(urlParameters));
for (NameValuePair h : headers)
{
httpPost.addHeader(h.getName(), h.getValue());
}
response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(response.getEntity().getContent())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try{
response.close();
httpClient.close();
}catch(Exception ex) {
ex.printStackTrace();
}
}
回答by GlobalVariable
The API you are invoking needs a query parameter called "query=true|false".
您正在调用的 API 需要一个名为“query=true|false”的查询参数。
URL url = new URL("https://appem.totango.com/api/v1/search/accounts/health_dist?query=true");
After adding this param, the HTTP request itself succeeds with status code 200, but the REST call fails with some server side error. Maybe you need a different payload.
添加此参数后,HTTP 请求本身成功,状态码为 200,但 REST 调用失败并出现一些服务器端错误。也许您需要不同的有效载荷。
I suggest if you are new to REST, try a REST client like POSTMan
我建议如果你是 REST 的新手,试试像POSTMan这样的 REST 客户端