2016-10-28 876 views
0

只是我试图访问URL即www.google.com ,我想捕获整个json响应作为输出... 我尝试了多个代码,这些代码帮助我仅查找响应代码,但我想完整的JSON响应,我可以从中筛选出一些信息。如何使用httprequest获取完整的json响应

上面,我是做了网络的东西..

+0

我没有得到正是你必须做的:要HTTP响应转换成JSON字符串或要捕获只HTTP响应至极的JSON格式? – Svech87

+0

是的,当我们点击任何url时,它响应json响应的interms,所以我想获得这些json响应。 ... –

+1

搜索“如何使用java发送请求” – dit

回答

0

我用ApacheHttpClient罐子(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字符串。

希望这有助于