3

I have a simple 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)) { 

I have to support UTF-8 encoding and encoding UrlEncodedFormEntity isn't enough, but it's not clear what must be done, following several options available

Using uriBuilder.setCharset:

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

Using http.protocol.content-charset parameter:

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

Or just adding Content-Type"` header:

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

Or use request.getParams():

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

Or other obvious solution I overlooked?

Ori Marko
  • 56,308
  • 23
  • 131
  • 233

2 Answers2

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

}

Output

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

I think this may be the solution.

You refer to above: https://www.urlencoder.io/java/

0

To properly encode I move to use parameters in List<NameValuePair> over URIBuilder

and then encode using

URLEncodedUtils.format(nameValuePairs, StandardCharsets.UTF_8.name());
Ori Marko
  • 56,308
  • 23
  • 131
  • 233