无法从URL捕获JSON响应

时间:2018-10-30 14:17:20

标签: java json http

我试图发出一个将返回JSON格式响应的请求。但是输出似乎不是json格式。请帮忙。

    String url = "http://httpbin.org/ip";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    // optional default is GET
    con.setRequestMethod("GET");
    //add request header
    con.setRequestProperty("User-Agent", "Mozilla/5.0");
    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'GET' request to URL : " + url);
    System.out.println("Response Code : " + responseCode);
    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    //print in String
    System.out.println(response.toString());

    //Read JSON response and print
    JSONObject myResponse = new JSONObject(response.toString());

1 个答案:

答案 0 :(得分:0)

似乎链接已损坏,因此输出错误