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?
// 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
I think this may be the solution.
You refer to above: https://www.urlencoder.io/java/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With