我正在尝试使用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
如果我直接在浏览器中输入网址,Google会给我一个没有问题的JSON文件。但是,如果我尝试使用Java访问该URL,则会收到错误的请求。我怎么解决这个问题?提前谢谢。
答案 0 :(得分:3)
您需要URL对您的URL的查询字符串部分进行编码。查看this question/answer了解实现此目的的一些方法。
答案 1 :(得分:1)
我解决了你的问题。我建议在apache http api上建立http-request。
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和浏览器获得的响应正文。