在 Java 中使用 URLEncodedUtils 解析汉字
Parse Chinese characters with URLEncodedUtils in Java
我有一个像
这样的 uri
http://localhost/?name=foo&value=bar
我用
org.apache.http.client.utils.URLEncodedUtils.parse(URI uri, String encoding)
获取 NameValuePairs 列表,效果很好。但是现在我还需要解析中文字符的可能性,例如:
http://localhost/?name=生产者&value=单车
但是 URLEncodedUtilsparse 无法正确解析这些字符。我如何检索它们并再次获取 NameValuePairs 列表?
你可以这样试试:
String query1 = URLEncoder.encode("生产者", "UTF-8");
String query2 = URLEncoder.encode("单车", "UTF-8");
String url = "http://localhost/?name=" + query1 + "&value=" + query2;
同时检查 java.net.URLEncoder
我遇到过类似的情况。 URLEncodedUtils 必须与 StringEntity 一起使用。 UrlEncodedFormEntity 已损坏。
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost postRequest = new HttpPost(
URL);
List<NameValuePair> param_data = new ArrayList<>();
param_data.add(new BasicNameValuePair("name", [STRING_FOREIGN CHARS));
String s = URLEncodedUtils.format(param_data, java.nio.charset.Charset.forName("UTF-8"));
StringEntity entity = new StringEntity(s, java.nio.charset.Charset.forName("UTF-8"));
postRequest.setEntity(entity); // don't use postRequest.setEntity(new UrlEncodedFormEntity(param_data));
HttpResponse response = httpClient.execute(postRequest);
..[snipped] do whatever you want with response
我有一个像
这样的 urihttp://localhost/?name=foo&value=bar
我用
org.apache.http.client.utils.URLEncodedUtils.parse(URI uri, String encoding)
获取 NameValuePairs 列表,效果很好。但是现在我还需要解析中文字符的可能性,例如:
http://localhost/?name=生产者&value=单车
但是 URLEncodedUtilsparse 无法正确解析这些字符。我如何检索它们并再次获取 NameValuePairs 列表?
你可以这样试试:
String query1 = URLEncoder.encode("生产者", "UTF-8");
String query2 = URLEncoder.encode("单车", "UTF-8");
String url = "http://localhost/?name=" + query1 + "&value=" + query2;
同时检查 java.net.URLEncoder
我遇到过类似的情况。 URLEncodedUtils 必须与 StringEntity 一起使用。 UrlEncodedFormEntity 已损坏。
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost postRequest = new HttpPost(
URL);
List<NameValuePair> param_data = new ArrayList<>();
param_data.add(new BasicNameValuePair("name", [STRING_FOREIGN CHARS));
String s = URLEncodedUtils.format(param_data, java.nio.charset.Charset.forName("UTF-8"));
StringEntity entity = new StringEntity(s, java.nio.charset.Charset.forName("UTF-8"));
postRequest.setEntity(entity); // don't use postRequest.setEntity(new UrlEncodedFormEntity(param_data));
HttpResponse response = httpClient.execute(postRequest);
..[snipped] do whatever you want with response