2016-10-28 9 views
0

単にURL www.google.com を押してみようとしていますが、出力としてjsonレスポンス全体をキャプチャしたいと考えています... 私はレスポンス私はいくつかの情報をフィルタリングすることができますから、完全なJSON応答が欲しいです。私は、Web用にやっている事上記httprequestを使用して完全なjson応答を取得するには

..

+0

私は正確にあなたがしなければならないものを取得していない:あなたは、JSON文字列にHTTPレスポンスを変換したいか、あなたはJSON形式でのみHTTP応答をキャプチャしているWICHたいですか? – Svech87

+0

はい..。私たちはどんなURLでもヒットしましたが、それはjsonレスポンスのintermsに応答しますので、私はこれらのjsonレスポンスを取得したいと思います。 ... –

+1

「javaでリクエストを送信する方法」を検索する – dit

答えて

0

私はApacheHttpClientジャー(バージョン4.5.1)を使用。また、HttpCoreライブラリ(私は4.4.3を使用)と他のapacheライブラリ(コーデックのようなもの)が必要になります。

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文字列を解析することができます:ここで

は、GETメソッドとPOSTメソッドです。

希望はこのことができます

関連する問題