您的位置:首页 > 理论基础 > 计算机网络

Android 中用HttpClient进行网络数据加载时,得到String乱码的问题

2016-04-10 12:22 573 查看
当我们用HttpClient进行String加载或者想要得到JSON字符串时,有时会出现得到的字符串乱码,代码如下:

public class HttpUtil {
public static String getJson(String path){

ByteArrayOutputStream baos=null;
String str=null;
try {
HttpGet get=new HttpGet(path);
HttpClient client=new DefaultHttpClient();
HttpResponse response=client.execute(get);
if(response.getStatusLine().getStatusCode()==200){
InputStream is=response.getEntity().getContent();
BufferedReader reader=new BufferedReader(new InputStreamReader(is));
baos=new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
while(reader.readLine()!=null){
baos.write(buffer, 0, buffer.length);
}
str=new String(buffer, "utf-8");
is.close();
reader.close();
baos.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str;

}

}

在上述代码中,如果将得到的Entity对象转换成流进行操作,很容易乱码,就算指定编码格式也会出现乱码情况,这种情况是有什么原因造成,目前我也不太清楚,所以如果出现乱码,用EntityUtils.toString(httpResponse.getEntity())方法,直接转成字符串,就不会出现乱码了!

try {
HttpGet get=new HttpGet(path);
HttpClient client=new DefaultHttpClient();
HttpResponse response=client.execute(get);
if(response.getStatusLine().getStatusCode()==200){
str=EntityUtils.toString(response.getEntity());
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息