【问题标题】:Unable to get JSON response from URLConnection无法从 URLConnection 获得 JSON 响应
【发布时间】:2016-06-16 11:59:32
【问题描述】:

我正在尝试使用 java URLConnection 读取来自 googleapi 的响应。

如果我在浏览器中查询 "https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url=https%3A%2F%2Fwww.zauq.se&strategy=mobilez"

我得到 JSON 格式的响应。

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "invalidParameter",
    "message": "Invalid string value: 'mobilez'. Allowed values: [desktop, mobile]",
    "locationType": "parameter",
    "location": "strategy"
   }
  ],
  "code": 400,
  "message": "Invalid string value: 'mobilez'. Allowed values: [desktop, mobile]"
 }
}

但是当我使用以下代码时。

URL url = null;
            System.setProperty("http.agent", "");

            url = new URL("https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url=https%3A%2F%2Fwww.zauq.se&strategy=mobilez");//"https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url=" + paramUrl + "&strategy=" + paramStrategy);
            URLConnection conn = url.openConnection();
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0");
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String strTemp = "";
            StringBuilder sb = new StringBuilder();

            while ((null != (strTemp = br.readLine())))
            {
                sb.append(strTemp);
                if (dump)
                {
                    System.out.println(strTemp);
                }
            }

我得到 IO 异常

java.io.IOException: Server returned HTTP response code: 400 for URL: https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url=https%3A%2F%2Fwww.zauq.se&strategy=mobilez
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1627)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
    at amirTest.PageSpeedCheck.main(PageSpeedCheck.java:62)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

/ 但我需要得到 JSON 响应。

请建议我需要做出哪些更改才能将 JSON 作为响应。

【问题讨论】:

  • “无效的字符串值:'mobilez'。允许的值:[desktop, mobile]”:消息足够清晰
  • 我猜你发送的是 mobilez 而不是 mobile。在下面查看我的答案
  • 请补充问题,错误是您想要的结果,但格式应该是 JSON。否则人们会尝试帮助您尝试使用不允许的 URL 的 HTTP/200 ;-)

标签: java json httprequest urlconnection


【解决方案1】:

将连接投射到 Http(s)URLConnection,并在出错时调用getErrorStream() 获取流。

【讨论】:

  • 谢谢,它成功了。输入流是 = null; if (conn.getResponseCode() == 400) { is = conn.getErrorStream();错误=真; } else { is = conn.getInputStream(); }
【解决方案2】:

【讨论】:

  • 我知道它错了,意味着我想得到错误信息。但该错误消息应该类似于我们在浏览器中收到的错误消息,JSON 响应。
【解决方案3】:

您的 API 调用中使用的参数错误,因此服务器正在返回状态码 400。这意味着这是一个错误的请求。

mobilz 应该是移动的。您使用的网址也不正确。

【讨论】:

  • 是的,示例主机错误,使用正确的 molie 参数时显示。
  • 我知道它错了,意味着我想得到错误信息。但该错误消息应该类似于我们在浏览器中收到的错误消息,JSON 响应。
【解决方案4】:

你只需要改变你的代码如下:

    BufferedReader reader = new BufferedReader(new InputStreamReader(((HttpURLConnection) (new URL("https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url=https%3A%2F%2Fwww.zauq.se&strategy=mobilez")).openConnection())
.getInputStream(), Charset.forName("UTF-8")));

查看原答案here

查看类似的 SO 问题如下:

URLConnection Error - java.io.IOException: Server returned HTTP response code: 400 for URL

Server returned HTTP response code: 400

【讨论】:

    【解决方案5】:

    感谢@JB Nizet

    当我尝试读取错误流时它起作用了。

                InputStream is = null;
                if (conn.getResponseCode() == 400)
                {
    
                    is = conn.getErrorStream();
                    error = true;
                } else
                {
                    is = conn.getInputStream();
                }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-05
      • 1970-01-01
      • 2020-08-25
      • 2021-07-18
      相关资源
      最近更新 更多