为什么如下方法把inputstream转为String的时候会出错?
本帖最后由 AA5279AA 于 2013-09-03 11:49:09 编辑
public String getWeatherJson(InputStream is) {
StringBuilder builder = new StringBuilder();
InputStream is = null;
try {
byte[] b = new byte[2048];
for (int n; (n = is.read(b)) != -1;) {
builder.append(new String(b, 0, n, "UTF-8"));
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return builder.toString();
}
is本来应该的输出为:
{"weatherinfo":{"city":"门头沟","city_en":"mentougou","date_y":"2013年9月3日","date":"","week":"星期二","fchh":"11","cityid":"101011400","temp1":"27C~18C","temp2":"22C~17C","temp3":"23C~17C","temp4":"29C~16C","temp5":"29C~17C","temp6":"28C~17C","tempF1":"80.6F~64.4F","tempF2":"71.6F~62.6F","tempF3":"73.4F~62.6F","tempF4":"84.2F~60.8F","tempF5":"84.2F~62.6F","tempF6":"82.4F~62.6F","weather1":"阵雨","weather2":"中雨转小雨","weather3":"小雨转多云","weather4":"晴","weather5":"晴","weather6":"晴转多云","img1":"3","img2":"99","img3":"8","img4":"7","img5":"7","img6":"1","img7":"0","img8":"99","img9":"0","img10":"99","img11":"0","img12":"1","img_single":"3","img_title1":"阵雨","img_title2":"阵雨","img_title3":"中雨","img_title4":"小雨","img_title5":"小雨","img_title6":"多云","img_title7":"晴","img_title8":"晴","img_title9":"晴","img_title10":"晴","img_title11":"晴","img_title12":"多云","img_title_single":"阵雨","wind1":"微风","wind2":"微风","wind3":"微风","wind4":"微风","wind5":"微风","wind6":"微风","fx1":"微风","fx2":"微风","fl1":"小于3级","fl2":"小于3级","fl3":"小于3级","fl4":"小于3级","fl5":"小于3级","fl6":"小于3级","index":"热","index_d":"天气热,建议着短裙、短裤、短薄外套、T恤等夏季服装。","index48":"较舒适","index48_d":"建议着薄外套、开衫牛仔衫裤等服装。年老体弱者应适当添加衣物,宜着夹克衫、薄毛衣等。","index_uv":"弱","index48_uv":"最弱","index_xc":"不宜","index_tr":"适宜","index_co":"较舒适","st1":"25","st2":"16","st3":"18","st4":"15","st5":"21","st6":"17","index_cl":"较不宜","index_ls":"不太适宜","index_ag":"易发"}}
但是实际上的输出是存在乱码,但是只是一两个字符乱码。
这个例子中乱码的部分是
,"wind1":"微风",中的“微”字无法正常显示。
但是通过上述方法如果复制文件的话正常。。
后来改成了如下方法:
public static String fromIputStreamToString(InputStream is){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i = -1;
try {
while ((i = is.read()) != -1) {
baos.write(i);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return baos.toString();