java - 如何确定 HttpClient PostMethod 的参数中包含 UTF-8 字符串?

标签 java apache-commons-httpclient

在我们的 web 应用程序中,我们必须通过 HttpClient 向网络上的端点发送 POST 请求,该端点将接收该请求并对其进行一些处理。我们在字符编码方面遇到了问题,并且我很难找到问题的答案。

我们在发送请求时使用了 postMethod.getParams().setContentCharset("UTF-8") 方法,但在接收端,字符似乎仍然采用 ISO 编码8859-1。我已经确定了这一点,因为当我检查接收端的字符串时,一旦我按照 https://stackoverflow.com/a/16549329/1130549 中找到的步骤操作,其中的垃圾字符就会消失。 。我需要在发送端采取任何额外的步骤来确保我实际上按照预期以 UTF-8 写入字符吗?我们现在所做的就是将 postMethod.addParameter(paramKey, paramValue) 与 native String 对象一起使用。

编辑:这是我们如何发送 POST 请求的一个非常简单的示例。无论如何,这些值是从 XMLBeans 对象中获取的。

PostMethod postMethod = new PostMethod(url);
postMethod.getParams().setContentCharset("UTF-8");
postMethod.addParameter("key1", "value1");
postMethod.addParameter("key2", "value2");

HttpClient httpClient = new HttpClient();
int status = httpClient.executeMethod(postMethod);

最佳答案

编辑 更简单的解决方案是对值进行编码

postMethod.addParameter("key1", URLEncoder.encode("value1","UTF-8"));

要正确编码 UTF-8,您可以使用 StringEntityNameValuePair 执行不同的操作,例如:

try (CloseableHttpClient httpClient = HttpClients.custom().build()) {
   URIBuilder uriBuilder = new URIBuilder(url);
   HttpHost target = new HttpHost(uriBuilder.getHost(), uriBuilder.getPort(), uriBuilder.getScheme());
   List<NameValuePair> nameValuePairs = new ArrayList<>();
   nameValuePairs.add(new BasicNameValuePair("key1", "value1"));
   nameValuePairs.add(new BasicNameValuePair("key2", "value2"));
   String entityValue = URLEncodedUtils.format(nameValuePairs, StandardCharsets.UTF_8.name());
   StringEntity entity = new StringEntity(entityValue, StandardCharsets.UTF_8.name());
   post.setEntity(entity);
   httpClient.execute(target, post);

关于java - 如何确定 HttpClient PostMethod 的参数中包含 UTF-8 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58915333/

相关文章:

Java、HTTP 和套接字 : When to stop reading the request but keep the socket open?

java - 如何接受 byte[] 作为对 POST 的响应

java - 帮助使用 Facebook REST API - 使用 HttpClient (Java) 发送通知。

Java HttpClient 3.1 多部分发布

apache - 如何使用 HTTP 客户端传递客户端证书?

java - 在所有方法中插入打印语句

java - Spring 启动 : How to override default properties in Unit tests

Java 将字节转换为字符 - 转换问题

java - Servlets , JPA - 登录问题

android - 如何从 Android 中的 NoHttpResponseException 获取 Http 状态代码?