gpt4 book ai didi

java - 使用参数调用 POST 方法时无法获得正确的响应

转载 作者:太空宇宙 更新时间:2023-11-04 09:20:31 25 4
gpt4 key购买 nike

尝试使用 main 方法调用 post 方法,但收到 400 Bad request。我正在使用下面的代码

private static String POST_URL = "http://localhost:8080/RestApi/api/v1/getDetails";

public static void main(String[] args) {
try {
sendPost();
} catch (Exception e) {
System.out.println("Exception occurred while calling service and exception is " + e);
}
}

private static void sendPost() throws Exception {
HttpPost post = new HttpPost(POST_URL);
post.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");

// add request parameter, form parameters
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("id", "1004906799"));
urlParameters.add(new BasicNameValuePair("identifer", "Customer"));

post.setEntity(new UrlEncodedFormEntity(urlParameters));

try (CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(post)) {

System.out.println(EntityUtils.toString(response.getEntity()));
}

}
> Response : HTTP/1.1 400 Bad Request [Connection: keep-alive,
> X-Powered-By: Undertow/1, Server: WildFly/8, Content-Length: 0, Date:
> Mon, 14 Oct 2019 09:44:34 GMT]

最佳答案

尝试设置编码。将 post.setEntity(new UrlEncodedFormEntity(urlParameters)); 行替换为

post.setEntity(new UrlEncodedFormEntity(urlParameters, "UTF-8"));

尚未运行,但应该可以工作。

关于java - 使用参数调用 POST 方法时无法获得正确的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58373940/

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