簡體   English   中英

為什么我收到HTTP 400錯誤請求

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM