HttpClient4.x中GET方式发送请求参数中文乱码处理

苦苦寻觅,找到处理 HttpClient4.x GET 方式发送请求参数中文乱码问题的方法(不是请求后返回结果乱码)

自己尝试对HttpGet对象添加头部设置字符编码均无效(当前测试版本为HttpClient-4.5.3

添加的jar包:httpclient-4.5.3.jar   httpcore-4.4.6   httpmime-4.5.3.jar

代码片段:

String httpUrl = "http://xxxxx.xxx";
String charset = "GBK"; //设置字符编码
CloseableHttpClient httpClient = HttpClients.createDefault();
// 请求参数封装  
List params = new ArrayList();  
params.add(new BasicNameValuePair("name", "寻寻觅觅"));
params.add(new BasicNameValuePair("age", "30"));
String str = ""; 
String result = "";
try {
	//转换为键值对  
	str = EntityUtils.toString(new UrlEncodedFormEntity(params, charset)); 
	HttpGet httpGet = new HttpGet(httpUrl+"?"+str);
	HttpResponse response = httpClient.execute(httpGet);
	if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 请求成功
		System.out.println(EntityUtils.toString(response.getEntity()));
	} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_BAD_REQUEST) {
		System.out.println(response.getStatusLine().toString());
	} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
		System.out.println(response.getStatusLine().toString());
	} else {
		...
	}
} catch (ClientProtocolException e) {
	e.printStackTrace();
} catch (IOException e) {
	e.printStackTrace();
}


你可能感兴趣的:(开篇,Java,随笔)