gpt4 book ai didi

java - 如何对 CloseableHttpClient 请求进行 UTF-8 编码

转载 作者:行者123 更新时间:2023-12-02 06:22:22 26 4
gpt4 key购买 nike

我有一个简单的帖子:

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");

或者我忽略的其他明显的解决方案?

最佳答案

// 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);
}

}

输出

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

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

您引用上面:https://www.urlencoder.io/java/

关于java - 如何对 CloseableHttpClient 请求进行 UTF-8 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55823342/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com