[英](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. 我正在尝试使用HTTP从Google趋势获取JSON响应。 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. 如果我直接在浏览器中输入URL,Google会为我提供一个JSON文件,没有问题。 However, if I try to access that URL using Java, I am given a bad request. 但是,如果尝试使用Java访问该URL,则会收到错误的请求。 How can I solve this problem? 我怎么解决这个问题? Thanks in advance. 提前致谢。
You need to URL Encode the query string portion of your URL. 您需要对URL的查询字符串部分进行URL编码。 Check out this question/answer for some ways to achieve this. 查看此问题/答案以了解实现此目的的一些方法。
I solved your problem. 我解决了你的问题。 I higly recomend http-request built on apache http api. 我高高兴兴地建议基于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);
}
The code prints the response code 200 and response body which you get by browser. 该代码打印您通过浏览器获得的响应代码200和响应正文。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.