gpt4 book ai didi

java - 无法从 URLConnection 获取 JSON 响应

转载 作者:行者123 更新时间:2023-12-01 18:04:24 25 4
gpt4 key购买 nike

我正在尝试使用 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 作为响应。

最佳答案

将连接转换为 Http(s)URLConnection,并调用 getErrorStream()在发生错误时获取流。

关于java - 无法从 URLConnection 获取 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37858575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com