码迷,mamicode.com
首页 > Web开发 > 详细

httpclient发送请求的几种方式

时间:2018-06-25 20:19:19      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:cli   ade   set   pack   app   connect   closeable   import   asi   

package asi;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class TestHttpClient {
    
 public static void main(String[] args){
  RequestConfig requestConfig = RequestConfig.custom()  
             .setSocketTimeout(150000)  
             .setConnectTimeout(150000)  
             .setConnectionRequestTimeout(150000)  
             .build();  
     CloseableHttpClient httpClient =  HttpClients.createDefault();
     CloseableHttpResponse response = null;  
     HttpEntity httpEntity = null;  
     String responseContent = null; 
     
  String url=...
  String json=...
  HttpPost httpPost=new HttpPost(url);  
     httpPost.addHeader("Content-type","application/json; charset=utf-8");  
  httpPost.setHeader("Accept", "application/json");
     try {  
         StringEntity stringEntity = new StringEntity(json, "UTF-8");  
         stringEntity.setContentType("application/x-www-form-urlencoded");  
         httpPost.setEntity(stringEntity);  
         httpPost.setConfig(requestConfig);         
         response = httpClient.execute(httpPost);  
         httpEntity = response.getEntity();  
         responseContent = EntityUtils.toString(httpEntity, "UTF-8");
     } catch (Exception e) {  
         e.printStackTrace();  
     }  
     System.out.println(responseContent);
 }
 
}

 

httpclient发送请求的几种方式

标签:cli   ade   set   pack   app   connect   closeable   import   asi   

原文地址:https://www.cnblogs.com/BonnieWss/p/9225702.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!