我想从使用HTTP的Google Trends获取JSON响应。这是我的代码片段:(Java)HTTP GET请求不断获得400响应代码,尽管链接在浏览器中工作得很好
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,谷歌给我也没有问题的JSON文件。但是,如果我尝试使用Java访问该URL,则会收到错误的请求。我怎么解决这个问题?提前致谢。
你可以尝试不回退斜杠在URL字符串中的双引号?尝试使用单引号,看看会发生什么? –
@ DanielH.J。我只是试了一下,但它不起作用 –
如果我正在阅读这个权利,你是说当你粘贴你的代码输出到浏览器的URL时,它会打开? – fuzzyblankey