JAVA HTTPS从URL获取JSON

时间:2014-12-13 10:39:23

标签: java json https

我正在尝试接收此网址的json:https://usecryptos.com/jsonapi/ticker/BTC-USD它可以通过浏览器访问,但是,我没有成功,有人可以发布代码吗?

2 个答案:

答案 0 :(得分:0)

我这样想:

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

答案 1 :(得分:0)

对于https,您应该使用HttpsUrlConnection,如下所示:

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