2016-09-05 3 views
1

bodyでHTTP Post Requestを作成しようとしています。私はjsonオブジェクトをリクエストのボディの中に入れ、それに応答してボディを読む方法を知りたいと思う。HTTPPostRequest Bodyにjsonを入れて本文を読み取って返信する方法

HttpClient httpClient = HttpClientBuilder.create().build(); 
    String responseString = null; 
    try { 
     HttpPost request = new HttpPost(link); 
     log.info("Executing request " + request.getRequestLine()); 
     StringEntity params = new StringEntity(data); 
     request.addHeader("content-type", "application/json"); 
     request.setEntity(params); 
     HttpResponse response = httpClient.execute(request); 
     HttpEntity entity = response.getEntity(); 
     responseString = EntityUtils.toString(entity, "UTF-8"); 
    } catch (Exception e) { 
     log.info("Exception thrown while executing HTTPPostRequest"); 
    } 
    return responseString; 

これは、現在リクエストしているコードスニペットです。 'StringEntity'を使用する場合は、データを本体の中に入れるのが適切です。 jsonデータを含む本体を返すべき空のボディが得られます

+1

これを確認してください:http://stackoverflow.com/questions/7181534/http-post-using-json-in-java –

答えて

0

あなたの 'data'がjsonであれば問題ありません。

HttpClient httpClient = HttpClientBuilder.create().build(); 
    String responseString = null; 
    try { 
     HttpPost request = new HttpPost(link); 
     log.info("Executing request " + request.getRequestLine()); 
     StringEntity content = new StringEntity(data); 
     content.setContentType("application/json"); 
     //or request.setHeader("Content-type", "application/json"); 
     request.setEntity(content); 
     HttpResponse response = httpClient.execute(request); 
     HttpEntity entity = response.getEntity(); 
     responseString = EntityUtils.toString(entity, "UTF-8"); 
    } catch (Exception e) { 
     log.info("Exception thrown while executing HTTPPostRequest"); 
    } 
    return responseString; 
関連する問題