我遇到以下代碼的一些問題。我正在嘗試閱讀以下Reddit網址如何從Android中的URL讀取json數據
https://www.reddit.com/r/earthporn/.json?after=
以下是未正確執行的代碼。
public static String readContents(String url){
try{
InputStream input= new URL(url).openStream();
Reader reader = new InputStreamReader(input);
BufferedReader in = new BufferedReader(reader);
String line, str;
str = "";
while ((line=in.readLine()) != null) {
str += line;
System.out.println(line);
}
return str;
}catch(IOException e){
Log.d("READ FAILED", e.toString());
return null;
}
}
}
這裏是我從
List<Post> fetchPosts(){
String raw=RemoteData.readContents(url);
List<Post> list=new ArrayList<Post>();
try{
JSONObject data=new JSONObject(raw).getJSONObject("data");
JSONArray children=data.getJSONArray("children");
//Using this property we can fetch the next set of
//posts from the same subreddit
after=data.getString("after");
for(int i=0;i<children.length();i++){
JSONObject cur=children.getJSONObject(i)
.getJSONObject("data");
Post p=new Post();
p.title=cur.optString("title");
p.url=cur.optString("url");
p.numComments=cur.optInt("num_comments");
p.points=cur.optInt("score");
p.author=cur.optString("author");
p.subreddit=cur.optString("subreddit");
p.permalink=cur.optString("permalink");
p.domain=cur.optString("domain");
p.id=cur.optString("id");
p.thumbnail=cur.optString("thumbnail");
if(p.title!=null)
list.add(p);
}
}catch(Exception e){
Log.e("fetchPosts()",e.toString());
}
return list;
}
有沒有人有任何線索爲什麼這不讀取任何東西?我希望我包含足夠的代碼以使其有意義。如果需要,請告訴我。
也確實相關,但' str =「」; while((line = in.readLine())!= null){str + = line;如果你正在閱讀長文件,''是非常糟糕的主意。由於每次調用'a = a +「b」時,不要使用串聯在循環中構建字符串結果「Java需要創建StringBuilder,它將複製舊值,追加新部分,然後根據該內容創建新的String迭代)。最好在循環之前創建一個StringBuilder,'在循環中追加所有部分並最終將其轉換爲toSring()'。 – Pshemo
您是否收到特定的錯誤或者它只是空的? –
由於HttpClient已被棄用,[這是一個很好的例子](https://stackoverflow.com/a/48426408/2263683)如何使用URLConnection來完成; –