【问题标题】:How to encode UTF-8 CloseableHttpClient request如何编码 UTF-8 CloseableHttpClient 请求
【发布时间】:2019-04-24 06:03:59
【问题描述】:

我有一个简单的 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


    【解决方案1】:
    // 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/

    【讨论】:

    • CloseableHttpClient有什么联系?
    • 我不确定这个解决方案,但您应该咨询:httpPost.addRequestHeader("Content-Type", "text/plain;charset=UTF-8");
    • 如果你包含的url是文本,你可以使用上面的代码。
    【解决方案2】:

    为了正确编码,我转而使用List&lt;NameValuePair&gt; 中的参数而不是URIBuilder

    然后使用

    编码
    URLEncodedUtils.format(nameValuePairs, StandardCharsets.UTF_8.name());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-24
      • 1970-01-01
      • 2015-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-30
      • 1970-01-01
      相关资源
      最近更新 更多