上一篇是自己写的网络Stream读取并转换成String的源代码,今天研究了一下新浪的写法,下面贴出来供大家参考>>:
/**
* Returns the response body as string.<br>
* Disconnects the internal HttpURLConnection silently.
* @return response body
* @throws WeiboException
*/
public String asString() throws WeiboException{
if(null == responseAsString){
BufferedReader br;
try {
InputStream stream = asStream();
if (null == stream) {
return null;
}
br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
StringBuffer buf = new StringBuffer();
String line;
while (null != (line = br.readLine())) {
buf.append(line).append("\n");
}
this.responseAsString = buf.toString();
if(Configuration.isDalvik()){
this.responseAsString = unescape(responseAsString);
}
log(responseAsString);
stream.close();
con.disconnect();
streamConsumed = true;
} catch (NullPointerException npe) {
// don't remember in which case npe can be thrown
throw new WeiboException(npe.getMessage(), npe);
} catch (IOException ioe) {
throw new WeiboException(ioe.getMessage(), ioe);
}
}
return responseAsString;
}
本文深入探讨了新浪如何优化网络Stream读取过程,将其转换为字符串。通过详细分析源代码,揭示了关键步骤,包括使用BufferedReader、InputStreamReader以及UTF-8编码,确保高效且准确地获取响应体内容。同时,文章特别关注了在不同环境(如Dalvik)下的特殊处理,确保代码的通用性和兼容性。
4245

被折叠的 条评论
为什么被折叠?



