2017-10-10 311 views
1

我想从使用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,则会收到错误的请求。我怎么解决这个问题?提前致谢。

+0

你可以尝试不回退斜杠在URL字符串中的双引号?尝试使用单引号,看看会发生什么? –

+0

@ DanielH.J。我只是试了一下,但它不起作用 –

+0

如果我正在阅读这个权利,你是说当你粘贴你的代码输出到浏览器的URL时,它会打开? – fuzzyblankey

回答

1

我解决了你的问题。我建议使用apache http api构建http-request

private static final HttpRequest<String> REQUEST = 
     HttpRequestBuilder.createGet("https://trends.google.com/trends/api/explore", String.class) 
       .addDefaultRequestParameter("hl", "en-US") 
       .addDefaultRequestParameter("tz", "240") 
       .responseDeserializer(ResponseDeserializer.ignorableDeserializer()) 
       .build(); 

public void send() { 
    ResponseHandler<String> responseHandler = REQUEST.execute("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\":\"\"}"); 
    System.out.println(responseHandler.getStatusCode()); 
    responseHandler.ifHasContent(System.out::println); 
} 

该代码打印您通过浏览器得到的响应代码200和响应正文。

相关问题