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

标签 java

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

相关文章:

java - 如何附加两个word文档的内容?

java - java创建文件时抛出什么异常

java - 我可以同时发布 Retrofit @Path 和 @Field 吗?

java - Swing GridBagLayout 表现出来

Java Swing : slightly modify existing keyboard behaviour?(右箭头最初应将光标设置为位置 0)

java - 在 Java 中查找数字的因数并保存到数组

java - 计算文本文件中的行数、单词数和字符数

java - 在 java 中使用 String 查询 Elasticsearch

java - 带签名 JNLP 模板的签名小程序会生成 java.lang.SecurityException

java - 如何使用 Jsoup 在元素之前插入标签