【发布时间】:2017-10-10 02:14:31
【问题描述】:
我正在尝试使用 HTTP 从 Google 趋势获取 JSON 响应。这是我的代码 sn-p:
public class TestClass {
public static void main(String[] args) throws Exception{
String address = "https://trends.google.com/trends/api/explore?hl=en-US&tz=240&req={\"comparisonItem\":[{\"keyword\":\"Miley\",\"geo\":\"US\",\"time\":\"2012-01-01 2014-01-01\"},{\"keyword\":\"Hannah Montana\",\"geo\":\"US\",\"time\":\"2012-01-01 2014-01-01\"}],\"category\":0,\"property\":\"\"}";
URL url = new URL(address);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("URL is "+address);
System.out.println("Response code is " + responseCode); }
}
这是输出:
URL is https://trends.google.com/trends/api/explore?hl=en-US&tz=240&req={"comparisonItem":[{"keyword":"Miley","geo":"US","time":"2012-01-01 2014-01-01"},{"keyword":"Hannah Montana","geo":"US","time":"2012-01-01 2014-01-01"}],"category":0,"property":""}
Response code is 400
如果我直接在浏览器中键入 URL,Google 会毫无问题地为我提供 JSON 文件。但是,如果我尝试使用 Java 访问该 URL,则会收到错误请求。我怎么解决这个问题?提前致谢。
【问题讨论】:
-
你能不能尽量不要用反斜杠转义 url 字符串中的双引号?尝试使用单引号,看看会发生什么?
-
@DanielH.J.我刚试了,还是不行
-
如果我没看错,您是说当您将代码输出的 URL 粘贴到它打开的浏览器中时?
-
@fuzzyblankey 没错
标签: java rest http httpurlconnection