我正在尝试从url获取json字符串,当我使用这行代码时,我的方法返回一个空字符串值:
String jsonStr = getJsonStringFromURL(url);
以下是我正在使用的方法:
public static String getJsonStringFromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jsonObject = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch (Exception e) {
return null;
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}
catch(Exception e) {
return null;
}
return result;
}
我有一个url变量,当我将url复制并粘贴到浏览器中时,它会返回并显示一个json字符串。任何建议或帮助将不胜感激。
答案 0 :(得分:0)
当BufferReader
关闭时,你要为结果赋值。这就是为什么你得到空值。
而不是分配result = sb.toString()
;在BufferReader
之外,在关闭它之前分配它。
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
System.out.println(result);// It will print you the value
is.close();
希望它有所帮助。