在Android开发中,以HttpPost方式向服务器上提交中文数据时,如果没有设置传输数据的编码类型,在服务端获取到的数据就会出现乱码。在涉及不同平台上的应用,我们尽量使用UTF-8编码格式传输中文数据,HttpPost方式传输中文指定编码可以参考以下方法:
/**
* 向服务端提交数据
*/
public void notesubmit(){
......
......
httpClient = new DefaultHttpClient();
post = new HttpPost(url);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
NameValuePair pair1 = new BasicNameValuePair("title","中文");
NameValuePair pair2 = new BasicNameValuePair("content","中文");
pairs.add(pair1);
pairs.add(pair2);
//以post方式传输数据到服务端
try {
HttpEntity entity = new UrlEncodedFormEntity(pairs,HTTP.UTF_8);//设置编码,防止中午乱码
post = new HttpPost(url);
post.setEntity(entity);
httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(post);
//服务端返回的数据
String data = EntityUtils.toString(response.getEntity());
......
......
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
// 释放连接
httpClient.getConnectionManager().shutdown();
}
}