我想從使用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