如何编码UTF-8 CloseableHttpClient请求

问题描述 投票:0回答:2

我有一个简单的POST:

String url = "https://mysite";
try (CloseableHttpClient httpClient = HttpClients.custom().build()) {   
   URIBuilder uriBuilder = new URIBuilder(url);
   HttpPost request = new HttpPost();
   List<NameValuePair> nameValuePairs = new ArrayList<>(params);
   request.setEntity(new UrlEncodedFormEntity(nameValuePairs, StandardCharsets.UTF_8.name()));
   String encodedAuthorization = URLEncoder.encode(data, StandardCharsets.UTF_8.name());

    request.addHeader("Authorization", encodedAuthorization);
   try (CloseableHttpResponse response = httpClient.execute(request)) { 

我必须支持UTF-8编码和编码UrlEncodedFormEntity是不够的,但不清楚必须做什么,遵循几个可用的选项

使用uriBuilder.setCharset

HttpPost request = new HttpPost(uriBuilder.setCharset(StandardCharsets.UTF_8)).build());

使用http.protocol.content-charset参数:

HttpPost request = new HttpPost(uriBuilder.setParameter("http.protocol.content-charset", "UTF-8").build());

或者只是添加Content-Type"` header

request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

或者使用request.getParams()

request.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
request.getParams().setParameter("http.protocol.content-charset", "UTF-8");

还是我忽略了其他明显的解决方案?

java utf-8 character-encoding apache-httpclient-4.x
2个回答
0
投票
// Method to encode a string value using `UTF-8` encoding scheme
private static String encodeValue(String value) {
    try {
        return URLEncoder.encode(value, StandardCharsets.UTF_8.toString());
    } catch (UnsupportedEncodingException ex) {
        throw new RuntimeException(ex.getCause());
    }
}

public static void main(String[] args) {
    String baseUrl = "https://www.google.com/search?q=";

    String query = "Hellö Wörld@Java";
    String encodedQuery = encodeValue(query); // Encoding a query string

    String completeUrl = baseUrl + encodedQuery;
    System.out.println(completeUrl);
}

}

Output

https://www.google.com/search?q=Hell%C3%B6+W%C3%B6rld%40Java

我认为这可能是解决方案。

你在上面提到:https://www.urlencoder.io/java/


0
投票

为了正确编码我移动使用List<NameValuePair>中的参数而不是URIBuilder

然后使用编码

URLEncodedUtils.format(nameValuePairs, StandardCharsets.UTF_8.name());
© www.soinside.com 2019 - 2024. All rights reserved.