我几天来一直在努力解决这个问题,但我似乎无法解决这个问题。
创建HttpURLConnection
到"http://goodmorningmartingrove.blogspot.ca/feeds/posts/default?alt=json"
后,我尝试读取数据,以便将其转换为JSONObject
,但方法getContentLength()
返回{{1} }}。我知道这是因为连接无法计算长度,但我不知道如何在-1
中没有缓冲区数组的长度来读取流。
我试过这个:
is.read(buf);
但阅读速度极慢。这是here的解释,但它没有解释如何为我的目的加快速度。我真的不知道该怎么做,所以任何帮助都会非常感激。谢谢!
修改
我收到了NullPointerException,但行号不准确。知道调用int nextCharacter;
String responseData = "";
while(true){
nextCharacter = reader.read();
if(nextCharacter == -1)
break;
responseData += (char) nextCharacter;
}
的地方吗?
代码:
length()
例外:
172 | String responseData = "";
173 | while ((responseData = reader.readLine()) != null);
174 | reader.close();
编辑#2
我设法解决了这个问题。例外是因为每次迭代循环时都会重新分配变量java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:156)
at org.json.JSONObject.<init>(JSONObject.java:173)
at com.mci.mymci.main.TempFakeRSS$PostGetterTask.doInBackground(TempFakeRSS.java:180)
at com.mci.mymci.main.TempFakeRSS$PostGetterTask.doInBackground(TempFakeRSS.java:155)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
。
对于其他人,这里是代码:
responseData
答案 0 :(得分:1)
改为使用BufferedReader
:
StringBuilder data = new StringBuilder();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(yourInputStream));
String line = "";
while ( (line = br.readLine()) != null) {
//do your processing here...
data.append(line);
}
} catch (...) {
//handle exceptions...
} finally {
if (br != null) {
br.close();
}
}
//the whole String content from the response is concatenated and stored in `data`
System.out.println(data.toString());