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

本文介绍使用HttpClient获取JSON字符串时可能出现的乱码问题及解决方案。通过对比两种不同的读取方式,指出直接使用EntityUtils.toString方法可以有效避免乱码问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当我们用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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值