[英]Why am I getting HTTP 400 bad request
我正在使用HTTP客户端(从http://www.mkyong.com/java/apache-httpclient-examples/复制的代码)发送帖子请求。 我一直在尝试将它与http://postcodes.io一起使用,以查找大量邮政编码,但失败了。 根据http://postcodes.io,我应该以以下JSON格式向http://api.postcodes.io/postcodes发送发布请求: {"postcodes" : ["OX49 5NU", "M32 0JG", "NE30 1DP"]}
但我总是得到HTTP响应代码400。我在下面包括了我的代码。 请告诉我我做错了什么? 谢谢
private void sendPost() throws Exception {
String url = "http://api.postcodes.io/postcodes";
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("postcodes", "[\"OX49 5NU\", \"M32 0JG\", \"NE30 1DP\"]"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
System.out.println("Reason : "
+ response.getStatusLine().getReasonPhrase());
BufferedReader br = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
result.append(line);
}
br.close();
System.out.println(result.toString());
}
这有效,不建议使用HTTP.UTF_8:
String url = "http://api.postcodes.io/postcodes";
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
StringEntity params =new StringEntity("{\"postcodes\" : [\"OX49 5NU\", \"M32 0JG\", \"NE30 1DP\"]}");
post.addHeader("Content-Type", "application/json");
post.setEntity(params);
Jon Skeet是正确的(通常,我可能会补充说),您基本上是在发送表单,并且默认情况下为form-url-encoding。 您可以尝试这样的方法:
String jsonString = "{\"postcodes\" : [\"OX49 5NU\", \"M32 0JG\", \"NE30 1DP\"]}";
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
post.setEntity(entity);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.