为什么我收到HTTP 400错误请求

时间:2015-01-24 21:57:33

标签: java post httpclient

我正在使用HTTP客户端(从http://www.mkyong.com/java/apache-httpclient-examples/复制的代码)来发送帖子请求。我一直试图将它与http://postcodes.io一起使用来查找大量的邮政编码但却失败了。根据{{​​3}},我应该使用以下JSON格式向http://postcodes.io发送帖子请求:{"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());
}

2 个答案:

答案 0 :(得分:2)

这样做,不推荐使用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);

答案 1 :(得分:1)

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);