如何从网站中读取价值

时间:2018-08-15 23:36:34

标签: android json jsoup

我只想读取(-1)值,这是网站上唯一的值,但我无法获取该值。任何伙伴都可以指导我如何进行操作。我在网络浏览器中粘贴API url时会得到它的值,而android无法获取它。 API的链接如下。

Link OF API

我正在尝试的代码是:

    private void getWebsite() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            final StringBuilder builder = new StringBuilder();

            try {
                Document doc = Jsoup.connect("https://api.thingspeak.com/channels/411172/feeds.json?results=1").get();
                String title = doc.title();
                Elements links = doc.select("[pre]");

                builder.append(title).append("\n");

                for (Element link : links) {
                    builder.append("\n").append("Link : ").append(link.attr("pre"))
                            .append("\n").append("Text : ").append(link.text());
                }
            } catch (IOException e) {
                builder.append("Error : ").append(e.getMessage()).append("\n");
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    result.setText(builder.toString());
                }
            });
        }
    }).start();
}

在浏览器中调用Web API的屏幕截图 Here is the picture of Web API call 我得到的错误是错误:HTTP错误:提取URL

1 个答案:

答案 0 :(得分:0)

我看到来自API的响应是JSON格式的,因此您必须按照以下步骤修改代码

private void getWebsite() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            final StringBuilder builder = new StringBuilder();

            try {
                Document doc = Jsoup.connect("https://api.thingspeak.com/channels/411172/feeds.json?results=1")
                        .ignoreContentType(true)
                        .get();
                String json = doc.body().text();
                builder.append(json);

            } catch (IOException e) {
                builder.append("Error : ").append(e.getMessage()).append("\n");
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    result.setText(builder.toString());
                }
            });
        }
    }).start();
}