【问题标题】:(Java) HTTP GET request keeps getting 400 response code despite the link working perfectly fine in browser(Java)尽管链接在浏览器中运行良好,但 HTTP GET 请求仍不断收到 400 响应代码
【发布时间】:2017-10-10 02:14:31
【问题描述】:

我正在尝试使用 HTTP 从 Google 趋势获取 JSON 响应。这是我的代码 sn-p:

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 字符串中的双引号?尝试使用单引号,看看会发生什么?
  • @DanielH.J.我刚试了,还是不行
  • 如果我没看错,您是说当您将代码输出的 URL 粘贴到它打开的浏览器中时?
  • @fuzzyblankey 没错

标签: java rest http httpurlconnection


【解决方案1】:

您需要对 URL 的查询字符串部分进行 URL 编码。查看this question/answer 了解实现此目的的一些方法。

【讨论】:

    【解决方案2】:

    我解决了你的问题。我强烈推荐 http-request 基于 apache http api。

    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 和响应正文。

    【讨论】:

      猜你喜欢
      • 2017-10-20
      • 1970-01-01
      • 1970-01-01
      • 2019-03-16
      • 1970-01-01
      • 2015-11-21
      • 2020-07-08
      • 2015-08-18
      • 1970-01-01
      相关资源
      最近更新 更多