Eddie Lin
Eddie Lin

Reputation: 310

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

I am trying to get a JSON response from Google Trends using HTTP. This is my code snippet:

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); }
}

This is the output:

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

If I type the URL directly in my browser, Google gives me a JSON file with no problem. However, if I try to access that URL using Java, I am given a bad request. How can I solve this problem? Thanks in advance.

Upvotes: 1

Views: 1915

Answers (2)

Beno
Beno

Reputation: 987

I solved your problem. I higly recomend http-request built on 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);
}

The code prints the response code 200 and response body which you get by browser.

Upvotes: 1

Catchwa
Catchwa

Reputation: 5855

You need to URL Encode the query string portion of your URL. Check out this question/answer for some ways to achieve this.

Upvotes: 3

Related Questions