簡體   English   中英

(Java)盡管該鏈接在瀏覽器中運行正常,但HTTP GET請求仍可獲取400個響應代碼

[英](Java) HTTP GET request keeps getting 400 response code despite the link working perfectly fine in browser

我正在嘗試使用HTTP從Google趨勢獲取JSON響應。 這是我的代碼段:

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的查詢字符串部分進行URL編碼。 查看此問題/答案以了解實現此目的的一些方法。

我解決了你的問題。 我高高興興地建議基於apache http api的http請求

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM