在我们的Web应用程序中,我们必须通过HttpClient向网络上的端点发送POST请求,该请求将接收到并进行一些处理。我们在字符编码方面遇到了麻烦,并且在寻找问题答案时也遇到了困难。
我们在发送请求时使用了postMethod.getParams().setContentCharset("UTF-8")
方法,但是在接收端,似乎字符仍然按照ISO 8859-1进行编码。我之所以这样确定,是因为当我在接收方检查String时,一旦我按照https://stackoverflow.com/a/16549329/1130549中的步骤进行操作,它中的垃圾字符就会消失。我需要在发送端采取任何额外的步骤来确保我实际上按预期的那样以UTF-8编写字符吗?我们现在要做的就是将postMethod.addParameter(paramKey, paramValue)
与本机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,您可以使用StringEntity
和NameValuePair
来执行不同的操作,例如:
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);