上一篇是自己写的网络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;
}