【发布时间】:2015-05-07 11:32:54
【问题描述】:
我正在尝试使用具有 JSON 有效负载的 POST 请求从 REST API 获取 JSON 响应(在发送之前应转换为 URL 编码文本)。我已经按照一些教程来实现该过程,但我收到状态码 400 的错误。我可能没有对给定的 JSON 字符串进行编码或遗漏了某些内容。请帮我解决这个问题。谢谢。
这是我的代码
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\":[\"mobile+testme@totango.com\"]}],\"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();
}
【问题讨论】:
-
您是否收到了响应正文以及 400 状态码?
-
@Dan675 不,只是状态码。
-
你没有在你的 os.flush() 之后调用 conn.connect(),我认为这可能是问题
-
@faljbour 添加了 conn.connect() 但仍然是相同的异常。
-
我刚试过你的代码,如果我删除 conn.RequestProperty("app-token",我得到一个错误 401 Unauthorized,但是当我把它放回去时,我得到了 400 错误的错误request.所以它与app-token有关