尝试使用 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/