java - Android 中如何从 URL 中读取 json 数据

标签 java android json url

我在使用以下代码时遇到了一些问题。我正在尝试从以下 Reddit URL 读取内容

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

调试时我得到以下结果: Raw 留空。 enter image description here

有没有人知道为什么它不阅读任何内容?我希望我包含了足够的代码以使其有意义。如果还需要,请告诉我。

最佳答案

您好,要获得响应,您必须打开一个 HttpsURLConnection,您遇到的问题是您从 URL 获得了空响应,因此您必须在此处使用适合我的代码:

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

    }

}

关于java - Android 中如何从 URL 中读取 json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43079460/

相关文章:

java - 使用 RTP 在 Java 或 C++ 中开发屏幕共享/演示应用程序的最佳方法是什么?

java - 如何使用 Selenium 在 Java 方法中初始化另一个 WebElement

java - Android:这个VideoView出了什么问题?

机器人 : checkboxes in a ListView ( strange behaviour of selected element)

ios - 使用时属性显示为零,但在使用前打印到调试控制台?

java程序读取特定数据

java - 如何防止 Spring 中所有的 Jackson 自动配置?

android - 在我的应用程序中使用 android 相机的混淆

html - 如何将我的 JSON 数据映射到 Angular 组件 .HTML 表

java - 将 json 对象发送到 Java 服务器独立应用程序时出错