我只是想点击网址,即www.google.com 我希望捕获整个json响应作为输出... 我尝试了多个代码,这些代码只能帮助我找到响应代码,但我想要完整的json响应,我可以从中过滤掉一些信息。
我正在为网络做的事情......
答案 0 :(得分:0)
我使用了ApacheHttpClient jar(版本4.5.1)。你还需要HttpCore库(我使用4.4.3)和其他一些apache库(比如编解码器)。
以下是GET方法和POST方法:
public static String getJsonStringHttpGet(String url,Map<String,String> headers) throws IOException {
BasicCookieStore cookieStore = new BasicCookieStore();
CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultCookieStore(cookieStore)
.build();
HttpCoreContext localContext = new HttpCoreContext();
HttpGet get = new HttpGet(url);
/*
* if you need to specify headers
*/
if (headers != null) {
for (String name : headers.keySet()) {
get.addHeader(name, headers.get(name));
}
}
HttpResponse response = httpClient.execute(get, localContext);
byte [] bytes = EntityUtils.toByteArray(response.getEntity());
return new String(bytes);
}
public static String getJsonStringHttpPost(String url,Map<String,String> postParams,Map<String,String> headers) throws IOException {
BasicCookieStore cookieStore = new BasicCookieStore();
CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultCookieStore(cookieStore)
.build();
HttpCoreContext localContext = new HttpCoreContext();
HttpPost post = new HttpPost(url);
/*
* adding some POST params
*/
if (postParams != null && postParams.size() > 0) {
List<BasicNameValuePair> postParameters = new ArrayList<>();
for (String name : postParams.keySet()) {
postParameters.add(new BasicNameValuePair(name, postParams.get(name)));
}
post.setEntity(new UrlEncodedFormEntity(postParameters));
}
/*
* if you need to specify headers
*/
if (headers != null) {
for (String name : headers.keySet()) {
post.addHeader(name, headers.get(name));
}
}
HttpResponse response = httpClient.execute(post, localContext);
byte [] bytes = EntityUtils.toByteArray(response.getEntity());
return new String(bytes);
}
然后你可以随意解析json字符串。
希望这有帮助