2017-03-28 2 views
0

다음 코드에 문제가 있습니다. 다음 Reddit URL에서 읽으려고합니다.Android에서 URL에서 json 데이터를 읽는 방법

https://www.reddit.com/r/earthporn/.json?after= 

다음은 올바르게 실행되지 않는 코드입니다. 원료가 비어 : 나는 다음과 같은 결과를 얻을 수 디버깅 할 때 내가

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; 
} 

에서 호출 할 경우 여기

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; 
     } 
    } 
} 

그리고이다. enter image description here

아무에게도 이것이 아무 것도 읽지 않는 이유에 대한 단서가 있습니까? 나는 그것을 이해하기에 충분한 코드를 포함 시켰 으면 좋겠다. 더 이상 필요하다면 알려주십시오.

+0

도 아니다 정말'관련이 있지만, str = ""; while ((line = in.readLine())! = null) {str + = line; ... '는 긴 파일을 읽는 중 아주 나쁜 생각입니다. 'a = a + "b" "를 호출 할 때마다 연결 문자열을 사용하여 루프에서 문자열 결과를 작성하지 마십시오. Java는 이전 값을 복사하고 새 부품을 추가 한 다음 해당 내용을 기반으로 새로운 String을 작성하는 StringBuilder를 작성해야합니다 되풀이). 하나의 StringBuilder before 루프를 만들고, 모든 파트를 루프에 '추가'한 다음, 마지막으로 toSring()을 변환하는 것이 더 좋습니다. – Pshemo

+0

특정 오류가 발생 했습니까 아니면 그냥 비어 있습니까? –

+0

HttpClient가 더 이상 사용되지 않으므로 URLConnection을 사용하여 HttpClient를 수행하는 방법에 대한 [좋은 예] (https://stackoverflow.com/a/48426408/2263683)를 참조하십시오. –

답변

1

안녕하세요 당신이 나를 위해 작동 코드 당신이 여기해야합니다, 그래서 당신은 URL에서 널 응답을 받고있는 문제 HttpsURLConnection의를 열어야합니다 응답을 얻을 수 있습니다 :

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 (line)의 문제점. – speedious

관련 문제