http网络连接中使用Apache方式HttpClient连接服务post传参乱码问题
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
BasicNameValuePair namePair = new BasicNameValuePair("name", "李四");
BasicNameValuePair passwordPair = new BasicNameValuePair("password",
"123");
ArrayList<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
list.add(namePair);
list.add(passwordPair);
关键代码: (访问HTML时)
// 乱码问题解决方法一
HttpEntity entity = new UrlEncodedFormEntity(list, HTTP.UTF_8); // 加上utf-8解决乱码问题,服务端也应加上req.setCharacterEncoding("UTF-8");
// 乱码问题解决方法二,服务端去掉req.setCharacterEncoding("UTF-8")时
post.setHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8");
post.setEntity(entity);
(访问文本,例如TXT时)
HttpResponse res = client.execute(post);
result = EntityUtils.toString(res.getEntity(),HTTP.UTF_8); //网络获取文本乱码解决