-1

I'm trying to receive the json of this url: https://usecryptos.com/jsonapi/ticker/BTC-USD It's accessible by browser, however, I haven't been successed, can someone post a code to do it?

Ernani
  • 1,009
  • 3
  • 15
  • 26

2 Answers2

0

I'm trying like this:

public static String getJSON(String url, int timeout) throws IOException {

    URL u = new URL(url);
    HttpURLConnection c = (HttpURLConnection) u.openConnection();
    c.setRequestMethod("GET");
    c.setRequestProperty("Content-length", "0");
    c.setUseCaches(false);
    c.setAllowUserInteraction(false);
    c.setConnectTimeout(timeout);
    c.setReadTimeout(timeout);
    c.connect();
    int status = c.getResponseCode();

    switch (status) {
        case 200:
        case 201:
            BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();
            return sb.toString();
    }

    return null;
}
Ernani
  • 1,009
  • 3
  • 15
  • 26
0

For https you should use the HttpsUrlConnection like this:

    URL u = new URL("https://blockchain.info/de/ticker");
    HttpsURLConnection conn = (HttpsURLConnection) u.openConnection();
    InputStream is = conn.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);

    String inputLine;

    while ((inputLine = br.readLine()) != null) {
        System.out.println(inputLine);
    }

    br.close();
    isr.close();
    is.close();
    conn.disconnect();
Chris
  • 158
  • 8