我在http get请求中使用了下面的代码,但是我从return中得到的是一个null.I,我不知道为什么。
public static String getResponseFromGetUrl(String url) throws Exception {
StringBuffer sb = new StringBuffer();
try {
HttpResponse httpResponse = httpclient.execute(httpRequest);
String inputLine = "";
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
InputStreamReader is = new InputStreamReader(httpResponse
.getEntity().getContent());
BufferedReader in = new BufferedReader(is);
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine);
}
in.close();
}
} catch (Exception e) {
e.printStackTrace();
return "net_error";
} finally {
httpclient.getConnectionManager().shutdown();
}
return sb.toString();
}我使用这个函数的原因是
String json_str = HttpUtils.getResponseFromGetUrl("www.xxx.com/start");
if ((json_str == null)) Log.d("Chen", "lastestTimestap----" + "json_str == null");有时日志总是printed.Not,实际上就像1%.But一样,我不知道为什么会这样。
发布于 2013-08-03 21:24:20
这段代码不会产生"null“。一定有更多的代码没有显示。
如果这就是您拥有的全部代码,我建议您删除StringBuffer并将其替换为
return "";更有可能的是,您忘记了提到一些代码,这些代码的作用类似于
Object o = null;
sb.append(o); // appears as "null"编辑:根据您的更新,我必须假设您正在读取类似于"null“的行。
您不太可能想要丢弃每行之间的换行符。我建议您也附加(“\n”),或者只记录您获得的所有文本,而不考虑新行。
顺便说一句,请不要使用StringBuffer,因为它的替代品StringBuilder已经存在了将近十年了。有一种常见的误解,认为使用StringBuffer有助于多线程,但更常见的情况是它会导致不正确的代码,因为在多线程上下文中正确使用StringBuffer即使不是不可能,也会非常困难
https://stackoverflow.com/questions/18033328
复制相似问题