简体   繁体   中英

android JSON from Url

So I am trying to retrieve JSON object from url. And I cannot retrieve anything from url. So to test why, I tried the same code on Spring application, and it works just fine. It crashes on code below only on android environment. Please help

    package com.example.sandbox;

    import org.json.JSONException;
    import org.json.JSONObject;

    import java.io.*;
    import java.net.URL;
    import java.nio.charset.Charset;

    private static String readAll(Reader rd) throws IOException {
                StringBuilder sb = new StringBuilder();
                int cp;
                while ((cp = rd.read()) != -1) {
                    sb.append((char) cp);
                }
                return sb.toString();
            }

            public JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
                InputStream is = new URL(url).openStream();
                try {
                    BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
                    String jsonText = readAll(rd);
                    JSONObject json = new JSONObject(jsonText);
                    return json;
                } finally {
                    is.close();
                }
            }











    }

Please check your internet connection and also check if you have added permission for INTERNET in your app's manifest that might be issue.
what error do you get exactly ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM