gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:16:44 27 4
gpt4 key购买 nike

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

关于java - 为什么我收到 HTTP 400 错误请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28130706/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com