2017-03-28 172 views
0

我遇到以下代碼的一些問題。我正在嘗試閱讀以下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; 
} 

稱之爲調試時,我得到以下結果: 原爲空。 enter image description here

有沒有人有任何線索爲什麼這不讀取任何東西?我希望我包含足夠的代碼以使其有意義。如果需要,請告訴我。

+0

也確實相關,但' str =「」; while((line = in.readLine())!= null){str + = line;如果你正在閱讀長文件,''是非常糟糕的主意。由於每次調用'a = a +「b」時,不要使用串聯在循環中構建字符串結果「Java需要創建StringBuilder,它將複製舊值,追加新部分,然後根據該內容創建新的String迭代)。最好在循環之前創建一個StringBuilder,'在循環中追加所有部分並最終將其轉換爲toSring()'。 – Pshemo

+0

您是否收到特定的錯誤或者它只是空的? –

+0

由於HttpClient已被棄用,[這是一個很好的例子](https://stackoverflow.com/a/48426408/2263683)如何使用URLConnection來完成; –

回答

1

您好得到響應,您必須打開一個HttpsURLConnection的,你必須是你得到從URL null響應,所以你必須在這裏是爲我工作的代碼的問題:

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 

import java.net.MalformedURLException; 
import java.net.URL; 


import javax.net.ssl.HttpsURLConnection; 


public class main { 
    public static String getJSON(String url) { 
     HttpsURLConnection con = null; 
     try { 
      URL u = new URL(url); 
      con = (HttpsURLConnection) u.openConnection(); 

      con.connect(); 


       BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); 
       StringBuilder sb = new StringBuilder(); 
       String line; 
       while ((line = br.readLine()) != null) { 
        sb.append(line + "\n"); 
       } 
       br.close(); 
       return sb.toString(); 


     } catch (MalformedURLException ex) { 
      ex.printStackTrace(); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } finally { 
      if (con != null) { 
       try { 
        con.disconnect(); 
       } catch (Exception ex) { 
        ex.printStackTrace(); 
       } 
      } 
     } 
     return null; 
    } 

    public static void main(String[] args) { 

     String url = "https://www.reddit.com/r/earthporn/.json?after="; 
     System.out.println(getJSON(url)); 

    } 

} 
+0

完美的作品!謝謝 –

+0

爲什麼我們在sb.append(line +「\ n」)中需要「\ n」? sb.append(行)有什麼問題。 – speedious