httpclient发送请求的几种方式

Posted bonniewss

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了httpclient发送请求的几种方式相关的知识,希望对你有一定的参考价值。

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发送请求的几种方式的主要内容,如果未能解决你的问题,请参考以下文章

.Net(C#)后台发送Get和Post请求的几种方法总结

golang基础-http请求的几种方式

golang基础-http请求的几种方式

异步发送请求的几种方式

前端向后端发送请求的几种方式

PHP发送HTTP请求的几种方式