2017-10-10 86 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和響應正文。

相關問題