【发布时间】:2015-07-27 22:22:36
【问题描述】:
我需要下载一个字符串中的 JSON,我几乎可以确定代码没有错,但是有些奇怪...
public boolean downloadJSON(){
json="";
try{
URL url = new URL(theURL);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = in.readLine()) != null) {
json+=line;
}
in.close();
return true;
} catch (Exception e) {
return false;
}
}
基本上它会正确打开缓冲区,正确读取 json 并将其存储在变量中,然后关闭流,然后返回 true 并且......它随机跳转到 return false 没有意义,而它在返回 false 异常 e 是... null O.o 这完全没有意义,请帮助我D:!!!
最后我是这样解决的:
public boolean downloadJSON(){
json="";
boolean out=false;
try{
URL url = new URL(theURL);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = in.readLine()) != null) {
json+=line;
}
in.close();
out = true;
} catch (Exception e) {
}
return out;
}
如果第一个不起作用,不要问我这应该如何正确,在我看来,我仍然认为第一个应该起作用:S
添加:为斯蒂芬 C:
public boolean downloadJSON(){
json="";
try{
URL url = new URL("http://fapfapfap.altervista.org/conapo/conapo.php?n="+numeroPagina);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = in.readLine()) != null){json+=line;}
in.close();
return true;
}catch (Exception e) {
Log.d("ERRORE", e.getStackTrace().toString());
return false;
}
}
【问题讨论】:
-
什么是 null O.o ?是 NullPointerException 吗?
-
不可能。如果返回 false,
e绝对不为空。在 catch 块中返回之前添加它。e.printStackTrace() -
可以提供网址吗?如果是离线 URL,是否只是返回 JSON?
-
url为:fapfapfap.altervista.org/conapo/conapo.php?n=1,被代码正确读取并保存在json字符串中
-
好吧,我解决了,但还是谢谢 :D
标签: java android json download