Springboot-发送HTTP请求两种方式

  • Spring生态内RestTemplate方式来发HTTP请求 

                

        //url       
         String url ="xxx";
        //定义参数
        Map<String, Object> params = new HashMap<>();
        params.put("xx", xx);
        params.put("xx", xx);
        params.put("xx", xx);
        //定义headers
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(params, headers);

        long start=System.currentTimeMillis();
        logger.info("==sendHttpPost 开始调用远程方法==");
        //执行HTTP请求
        try {
        	ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
            JSONObject jsonObject = JSONObject.parseObject(response.getBody());
            //json对象转Map
            Map<String, Object> map = (Map<String, Object>) jsonObject;
            if (200 == ParamsUtils.getIntParam(map.get("code"), 0)) {
                return ResultUtil.successResult(map.get("data"));
            }

            return ResultUtil.errorResult(map.get("msg"));
        } catch (RestClientException e) {
            logger.error(e.getMessage());
            return ResultUtil.errorResult("接口服务器异常");
        }finally {
            long end=System.currentTimeMillis();
            logger.info("==sendHttpPost 调用远程方法结束==");
            logger.info("==sendHttpPost cost=="+(end-start));
        }

  • apache的HttpClient开发方式来发HTTP请求  
    • import org.apache.commons.lang3.StringUtils;
      import org.apache.http.*;
      import org.apache.http.client.config.RequestConfig;
      import org.apache.http.client.entity.UrlEncodedFormEntity;
      import org.apache.http.client.methods.*;
      import org.apache.http.client.utils.URIBuilder;
      import org.apache.http.conn.ConnectTimeoutException;
      import org.apache.http.conn.ssl.NoopHostnameVerifier;
      import org.apache.http.entity.ContentType;
      import org.apache.http.entity.StringEntity;
      import org.apache.http.entity.mime.FormBodyPart;
      import org.apache.http.entity.mime.FormBodyPartBuilder;
      import org.apache.http.entity.mime.HttpMultipartMode;
      import org.apache.http.entity.mime.MultipartEntityBuilder;
      import org.apache.http.entity.mime.content.FileBody;
      import org.apache.http.entity.mime.content.StringBody;
      import org.apache.http.impl.client.CloseableHttpClient;
      import org.apache.http.impl.client.HttpClients;
      import org.apache.http.message.BasicNameValuePair;
      import org.apache.http.ssl.SSLContexts;
      import org.apache.http.ssl.TrustStrategy;
      import org.apache.http.util.EntityUtils;
      import org.slf4j.Logger;
      import org.slf4j.LoggerFactory;
      
      import javax.net.ssl.SSLContext;
      import java.io.File;
      import java.io.IOException;
      import java.io.UnsupportedEncodingException;
      import java.net.Socket;
      import java.net.SocketTimeoutException;
      import java.nio.charset.Charset;
      import java.security.cert.CertificateException;
      import java.security.cert.X509Certificate;
      import java.util.*;
      import java.util.Map.Entry;
      
      public class HttpClientUtils
      {
      	private static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);
      	// 编码格式。发送编码格式统一用UTF-8
      	private static final String ENCODING = "UTF-8";
      	
      	// 设置连接超时时间,单位毫秒。
      	private static final int CONNECT_TIMEOUT = 60000;
      	
      	// 请求获取数据的超时时间(即响应时间),单位毫秒。
      	private static final int SOCKET_TIMEOUT = 60000;
      	
      	/**
      	 * 发送get请求;不带请求头和请求参数
      	 * 
      	 * @param url
      	 *            请求地址
      	 * @return
      	 * @throws Exception
      	 */
      	public static HttpClientResult doGet(String url) throws Exception
      	{
      		return doGet(url, null, null);
      	}
      	
      	/**
      	 * 发送get请求;带请求参数
      	 * 
      	 * @param url
      	 *            请求地址
      	 * @param params
      	 *            请求参数集合
      	 * @return
      	 * @throws Exception
      	 */
      	public static HttpClientResult doGet(String url, Map<String, String> params) throws Exception
      	{
      		return doGet(url, null, params);
      	}
      	
      	/**
      	 * 发送get请求;带请求头和请求参数
      	 * 
      	 * @param url
      	 *            请求地址
      	 * @param headers
      	 *            请求头集合
      	 * @param params
      	 *            请求参数集合
      	 * @return
      	 * @throws Exception
      	 */
      	private static HttpClientResult doGet(String url, Map<String, String> headers,
      			Map<String, String> params)
      	{
      		try(CloseableHttpClient httpClient = HttpClients.createDefault();
      			CloseableHttpResponse httpResponse = null;)
      		{
      
      		// 创建访问的地址
      		URIBuilder uriBuilder = new URIBuilder(url);
      		if (params != null)
      		{
      			Set<Entry<String, String>> entrySet = params.entrySet();
      			for (Entry<String, String> entry : entrySet)
      			{
      				uriBuilder.setParameter(entry.getKey(), entry.getValue());
      			}
      		}
      		
      		// 创建http对象
      		HttpGet httpGet = new HttpGet(uriBuilder.build());
      		/**
      		 * setConnectTimeout:设置连接超时时间,单位毫秒。
      		 * setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
      		 * 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
      		 * setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。
      		 * 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
      		 */
      		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
      				.setSocketTimeout(SOCKET_TIMEOUT).build();
      		httpGet.setConfig(requestConfig);
      		
      		// 设置请求头
      		packageHeader(headers, httpGet);
      
      		// 执行请求并获得响应结果
      			return getHttpClientResult(httpResponse, httpClient, httpGet);
      		}catch (Exception e){
      			logger.warn(e.getMessage());
      		}
      		return new  HttpClientResult();
      	}
      
          public static HttpClientResult doGet(CloseableHttpClient httpClient, String url, Map<String, String> headers,
                                               Map<String, String> params) throws Exception
          {
              // 创建访问的地址
              URIBuilder uriBuilder = new URIBuilder(url);
              if (params != null)
              {
                  Set<Entry<String, String>> entrySet = params.entrySet();
                  for (Entry<String, String> entry : entrySet)
                  {
                      uriBuilder.setParameter(entry.getKey(), entry.getValue());
                  }
              }
      
              // 创建http对象
              HttpGet httpGet = new HttpGet(uriBuilder.build());
              /**
               * setConnectTimeout:设置连接超时时间,单位毫秒。
               * setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
               * 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
               * setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。
               * 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
               */
              RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
                      .setSocketTimeout(SOCKET_TIMEOUT).build();
              httpGet.setConfig(requestConfig);
      
              // 设置请求头
              packageHeader(headers, httpGet);
      
              // 创建httpResponse对象
              CloseableHttpResponse httpResponse = null;
      
              try
              {
                  // 执行请求并获得响应结果
                  return getHttpClientResult(httpResponse, httpClient, httpGet);
              }
              finally
              {
                  // 释放资源
                  release(httpResponse, httpClient);
              }
          }
      	
      	/**
      	 * 发送post请求;不带请求头和请求参数
      	 * 
      	 * @param url
      	 *            请求地址
      	 * @return
      	 * @throws Exception
      	 */
      	public static HttpClientResult doPost(String url) throws Exception
      	{
      		return doPost(url, null, new HashMap<String, String>());
      	}
      	
      	/**
      	 * 发送post请求;带请求参数
      	 * 
      	 * @param url
      	 *            请求地址
      	 * @param params
      	 *            参数集合
      	 * @return
      	 * @throws Exception
      	 */
      	public static HttpClientResult doPost(String url, Map<String, String> params) throws Exception
      	{
      		return doPost(url, null, params);
      	}
      
          /*入参说明
           *
           * param url 请求地址
           * param map 请求的Map<String, Object>数据
           *
           * */
          public static String sendPost(String url, Map<String, Object> map) {
              CloseableHttpClient httpClient = null;
              HttpPost httpPost = null;
              String result = null;
              try {
                  httpClient = HttpClients.createDefault();
                  httpPost = new HttpPost(url);//设置参数
                  List<NameValuePair> list = new ArrayList<NameValuePair>();
                  Iterator iterator = map.entrySet().iterator();
                  while (iterator.hasNext()) {
                      Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator.next();
                      list.add(new BasicNameValuePair(elem.getKey(), String.valueOf(elem.getValue())));
                  }
                  if (list.size() > 0) {
                      UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,"UTF-8");
                      httpPost.setEntity(entity);
                  }
                  HttpResponse response = httpClient.execute(httpPost);
                  if (response != null) {
                      HttpEntity resEntity = response.getEntity();
                      if (resEntity != null) {
                          result = EntityUtils.toString(resEntity, "UTF-8");
                      }
                  }
              } catch (Exception ex) {
                  ex.printStackTrace();
              }
              return result;
          }
      	
      	public static HttpClientResult doPost(CloseableHttpClient httpClient, String url, Map<String, String> params) throws Exception
      	{
      		return doPost(httpClient, url, null, params);
      	}
      	
      	/**
      	 * 发送post请求;带请求头和请求参数
      	 * 
      	 * @param url
      	 *            请求地址
      	 * @param headers
      	 *            请求头集合
      	 * @param params
      	 *            请求参数集合
      	 * @return
      	 * @throws Exception
      	 */
      	private static HttpClientResult doPost(String url, Map<String, String> headers,
      			Map<String, String> params)
      	{
      		try(CloseableHttpClient httpClient = HttpClients.createDefault();
      			CloseableHttpResponse httpResponse = null;){
      			// 创建httpClient对象
      
      
      			// 创建http对象
      			HttpPost httpPost = new HttpPost(url);
      			/**
      			 * setConnectTimeout:设置连接超时时间,单位毫秒。
      			 * setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
      			 * 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
      			 * setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。
      			 * 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
      			 */
      			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
      					.setSocketTimeout(SOCKET_TIMEOUT).build();
      			httpPost.setConfig(requestConfig);
      			// 设置请求头
      			/*
      			 * httpPost.setHeader("Cookie", ""); httpPost.setHeader("Connection",
      			 * "keep-alive"); httpPost.setHeader("Accept", "application/json");
      			 * httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
      			 * httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
      			 * httpPost.setHeader("User-Agent",
      			 * "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"
      			 * );
      			 */
      			packageHeader(headers, httpPost);
      			// 封装请求参数
      			packageParam(params, httpPost);
      
      			// 创建httpResponse对象
      
      
      				// 执行请求并获得响应结果
      			return getHttpClientResult(httpResponse, httpClient, httpPost);
      
      		}catch (Exception e){
      			logger.warn(e.getMessage());
      		}
      		return new HttpClientResult();
      	}
      	
      	public static HttpClientResult doPost(CloseableHttpClient httpClient, String url, Map<String, String> headers,
      			Map<String, String> params) throws Exception
      	{
      		// 创建http对象
      		HttpPost httpPost = new HttpPost(url);
      		/**
      		 * setConnectTimeout:设置连接超时时间,单位毫秒。
      		 * setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
      		 * 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
      		 * setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。
      		 * 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
      		 */
      		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
      				.setSocketTimeout(SOCKET_TIMEOUT).build();
      		httpPost.setConfig(requestConfig);
      		// 设置请求头
      		/*
      		 * httpPost.setHeader("Cookie", ""); httpPost.setHeader("Connection",
      		 * "keep-alive"); httpPost.setHeader("Accept", "application/json");
      		 * httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
      		 * httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
      		 * httpPost.setHeader("User-Agent",
      		 * "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"
      		 * );
      		 */
      		packageHeader(headers, httpPost);
      		// 封装请求参数
      		packageParam(params, httpPost);
      		
      		// 创建httpResponse对象
      		CloseableHttpResponse httpResponse = null;
      		
      		try
      		{
      			// 执行请求并获得响应结果
      			return getHttpClientResult(httpResponse, httpClient, httpPost);
      		}
      		finally
      		{
      			// 释放资源
      			release(httpResponse, httpClient);
      		}
      	}
      	
      	public static HttpClientResult doPost(CloseableHttpClient httpClient, String url,
      			Map<String, String> headers, String jsonString) throws Exception
      	{
      		// 创建http对象
      		HttpPost httpPost = new HttpPost(url);
      		/**
      		 * setConnectTimeout:设置连接超时时间,单位毫秒。
      		 * setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
      		 * 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
      		 * setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。
      		 * 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
      		 */
      		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
      				.setSocketTimeout(SOCKET_TIMEOUT).build();
      		httpPost.setConfig(requestConfig);
      		// 设置请求头
      		/*
      		 * httpPost.setHeader("Cookie", ""); httpPost.setHeader("Connection",
      		 * "keep-alive"); httpPost.setHeader("Accept", "application/json");
      		 * httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
      		 * httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
      		 * httpPost.setHeader("User-Agent",
      		 * "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"
      		 * );
      		 */
      		packageHeader(headers, httpPost);
      		httpPost.setHeader("Content-Type", "application/json");
      		// 封装请求参数
      		httpPost.setEntity(new StringEntity(jsonString, ENCODING));
      		
      		// 创建httpResponse对象
      		CloseableHttpResponse httpResponse = null;
      		
      		try
      		{
      			// 执行请求并获得响应结果
      			return getHttpClientResult(httpResponse, httpClient, httpPost);
      		}
      		finally
      		{
      			// 释放资源
      			release(httpResponse, httpClient);
      		}
      	}
      	
      	public static HttpClientResult doPost(String url, Map<String, String> headers,
      			String jsonString)
      	{
      		try(CloseableHttpClient httpClient = HttpClients.createDefault();
      			CloseableHttpResponse httpResponse = null;){
      			// 创建http对象
      			HttpPost httpPost = new HttpPost(url);
      			/**
      			 * setConnectTimeout:设置连接超时时间,单位毫秒。
      			 * setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
      			 * 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
      			 * setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。
      			 * 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
      			 */
      			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
      					.setSocketTimeout(SOCKET_TIMEOUT).build();
      			httpPost.setConfig(requestConfig);
      			// 设置请求头
      			/*
      			 * httpPost.setHeader("Cookie", ""); httpPost.setHeader("Connection",
      			 * "keep-alive"); httpPost.setHeader("Accept", "application/json");
      			 * httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
      			 * httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
      			 * httpPost.setHeader("User-Agent",
      			 * "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"
      			 * );
      			 */
      			packageHeader(headers, httpPost);
      			httpPost.setHeader("Content-Type", "application/json");
      			// 封装请求参数
      			httpPost.setEntity(new StringEntity(jsonString, ENCODING));
      			// 执行请求并获得响应结果
      			return getHttpClientResult(httpResponse, httpClient, httpPost);
      
      		}catch (SocketTimeoutException es) {
      			logger.warn("服务器响应超时 es={}",es.getMessage());
      		}catch (ConnectTimeoutException ex) {
      			logger.warn("服务器请求超时 ex={}",ex.getMessage());
      		}catch (Exception e){
      			logger.warn(e.getMessage());
      		}
      		return new HttpClientResult();
      	}
      
      
      	public static HttpClientResult doPost(String url, HttpEntity entity) {
      		return  doPost(url, null, entity);
      	}
      
      	public static HttpClientResult doPost(String url, Map<String, String> headers, HttpEntity entity) {
      		try(CloseableHttpClient httpClient = HttpClients.createDefault();
      			CloseableHttpResponse httpResponse = null){
      			// 创建http对象
      			HttpPost httpPost = new HttpPost(url);
      			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
      					.setSocketTimeout(SOCKET_TIMEOUT).build();
      			httpPost.setConfig(requestConfig);
      			// 设置请求头
      			httpPost.setHeader("Cookie", "");
      			httpPost.setHeader("Connection", "keep-alive");
      			httpPost.setHeader("Accept", "*/*");
      			httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
      			httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
      			httpPost.setHeader("User-Agent",
      			  "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"
      			 );
      			packageHeader(headers, httpPost);
      			// 封装请求参数
      			httpPost.setEntity(entity);
      			// 执行请求并获得响应结果
      			return getHttpClientResult(httpResponse, httpClient, httpPost);
      		}catch (Exception e){
      			logger.error(e.getMessage());
      		}
      		return new HttpClientResult();
      	}
      
      	/**
      	 * 发送post请求;带请求头和请求参数(参数为File)
      	 *
      	 * @param url 请求地址
      	 * @param headers 请求头集合
      	 * @param fileUrl 请求参数文件
      	 * @return
      	 * @throws Exception
      	 */
      	public static HttpClientResult doPostFile(String url, Map<String, String> headers, String fileUrl, String jsonStr, Integer jsonLen) {
      		try (CloseableHttpClient httpClient = HttpClients.createDefault();
      			 CloseableHttpResponse httpResponse = null;) {
      			// 创建http对象
      			HttpPost httpPost = new HttpPost(url);
      			/**
      			 * setConnectTimeout:设置连接超时时间,单位毫秒。
      			 * setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
      			 * 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
      			 * setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
      			 */
      			RequestConfig requestConfig =
      					RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
      			httpPost.setConfig(requestConfig);
      			// 设置请求头
      			/*httpPost.setHeader("Cookie", "");
      			httpPost.setHeader("Connection", "keep-alive");
      			httpPost.setHeader("Accept", "application/json");
      			httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
      			httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
      			httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325
      			.181 Safari/537.36");
      			*/
      			packageHeader(headers, httpPost);
      
      			// 封装请求参数
      			packageParamForFile(fileUrl, httpPost, jsonStr, jsonLen);
      
      			try {
      				// 执行请求并获得响应结果
      				return getHttpClientResult(httpResponse, httpClient, httpPost);
      			} finally {
      				// 释放资源
      				release(httpResponse, httpClient);
      			}
      		} catch (Exception e) {
      			logger.error(e.getMessage());
      		}
      		return new HttpClientResult();
      	}
      
      	/**
      	 * Description: 封装请求参数(参数为File)
      	 *
      	 * @param
      	 * @param httpMethod
      	 * @throws UnsupportedEncodingException
      	 */
      	public static void packageParamForFile(String fileUrl, HttpEntityEnclosingRequestBase httpMethod,String jsonStr,Integer jsonLen){
      		try {
      			FileBody bin = new FileBody(new File(fileUrl));
      			StringBody comment = new StringBody("This is comment", ContentType.TEXT_PLAIN);
      			// 封装请求参数
      			MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create()
      					.setCharset(Charset.forName("UTF-8"))
      					.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
      					.addPart("file", bin)
      					.addPart("comment", comment);
      			if (StringUtils.isNotEmpty(jsonStr)) {
      				FormBodyPart formBodyPart = FormBodyPartBuilder.create().setName("blh").setBody(new StringBody(jsonStr,
      						ContentType.DEFAULT_TEXT)).build();
      				multipartEntityBuilder.addPart(formBodyPart);
                  }
      			if (null !=jsonLen) {
      				FormBodyPart formBodyPart2 = FormBodyPartBuilder.create().setName("index").setBody(new StringBody(String.valueOf(jsonLen),
      						ContentType.DEFAULT_TEXT)).build();
      				multipartEntityBuilder.addPart(formBodyPart2);
      			}
      			// 设置到请求的http对象中
      			httpMethod.setEntity(multipartEntityBuilder.build());
      		} catch (Exception e) {
      			logger.error("packageParamForFile={}",e.getMessage());
      		}
      	}
      	
      	public static HttpClientResult doPost(String url, Map<String, String> headers,
      			String jsonString, Map<String, String> params)
      	{
      		try(CloseableHttpClient httpClient = HttpClients.createDefault();
      			CloseableHttpResponse httpResponse = null;){
      			// 创建httpClient对象
      
      			// 创建访问的地址
      			URIBuilder uriBuilder = new URIBuilder(url);
      			if (params != null)
      			{
      				Set<Entry<String, String>> entrySet = params.entrySet();
      				for (Entry<String, String> entry : entrySet)
      				{
      					uriBuilder.setParameter(entry.getKey(), entry.getValue());
      				}
      			}
      
      			// 创建http对象
      			HttpPost httpPost = new HttpPost(uriBuilder.build());
      			/**
      			 * setConnectTimeout:设置连接超时时间,单位毫秒。
      			 * setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
      			 * 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
      			 * setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。
      			 * 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
      			 */
      			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
      					.setSocketTimeout(SOCKET_TIMEOUT).build();
      			httpPost.setConfig(requestConfig);
      			// 设置请求头
      			/*
      			 * httpPost.setHeader("Cookie", ""); httpPost.setHeader("Connection",
      			 * "keep-alive"); httpPost.setHeader("Accept", "application/json");
      			 * httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
      			 * httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
      			 * httpPost.setHeader("User-Agent",
      			 * "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"
      			 * );
      			 */
      			packageHeader(headers, httpPost);
      			httpPost.setHeader("Content-Type", "application/json");
      			// 封装请求参数
      			httpPost.setEntity(new StringEntity(jsonString, ENCODING));
      
      			// 创建httpResponse对象
      
      
      
      			// 执行请求并获得响应结果
      			return getHttpClientResult(httpResponse, httpClient, httpPost);
      		}catch (Exception e){
      			logger.warn(e.getMessage());
      		}
      		return new HttpClientResult();
      	}
      	
      	/**
      	 * 发送put请求;不带请求参数
      	 * 
      	 * @param url
      	 *            请求地址
      	 *
      	 * @return 请求结果
      	 */
      	public static HttpClientResult doPut(String url) {
      		return doPut(url);
      	}
      	
      	/**
      	 * 发送put请求;带请求参数
      	 * 
      	 * @param url
      	 *            请求地址
      	 * @param params
      	 *            参数集合
      	 * @return
      	 * @throws Exception
      	 */
      	public static HttpClientResult doPut(String url, Map<String, String> params) throws Exception
      	{
      		try (CloseableHttpClient httpClient = HttpClients.createDefault();
      			 CloseableHttpResponse httpResponse = null;){
      
      			HttpPut httpPut = new HttpPut(url);
      			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
      					.setSocketTimeout(SOCKET_TIMEOUT).build();
      			httpPut.setConfig(requestConfig);
      
      			packageParam(params, httpPut);
      
      
      
      
      			return getHttpClientResult(httpResponse, httpClient, httpPut);
      
      		}catch (Exception e){
      			logger.warn(e.getMessage());
      		}
      
      		return new HttpClientResult();
      	}
      	
      	/**
      	 * 发送delete请求;不带请求参数
      	 * 
      	 * @param url
      	 *            请求地址
      	 *            参数集合
      	 * @return
      	 * @throws Exception
      	 */
      	public static HttpClientResult doDelete(String url) throws Exception
      	{
      		CloseableHttpClient httpClient = HttpClients.createDefault();
      		HttpDelete httpDelete = new HttpDelete(url);
      		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
      				.setSocketTimeout(SOCKET_TIMEOUT).build();
      		httpDelete.setConfig(requestConfig);
      		
      		CloseableHttpResponse httpResponse = null;
      		try
      		{
      			return getHttpClientResult(httpResponse, httpClient, httpDelete);
      		}
      		finally
      		{
      			release(httpResponse, httpClient);
      		}
      	}
      	
      	/**
      	 * 发送delete请求;带请求参数
      	 * 
      	 * @param url
      	 *            请求地址
      	 * @param params
      	 *            参数集合
      	 * @return
      	 * @throws Exception
      	 */
      	public static HttpClientResult doDelete(String url, Map<String, String> params) throws Exception
      	{
      		if (params == null)
      		{
      			params = new HashMap<String, String>();
      		}
      		
      		params.put("_method", "delete");
      		return doPost(url, params);
      	}
      	
      	/**
      	 * Description: 封装请求头
      	 * 
      	 * @param params
      	 * @param httpMethod
      	 */
      	public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod)
      	{
      		// 封装请求头
      		if (params != null)
      		{
      			Set<Entry<String, String>> entrySet = params.entrySet();
      			for (Entry<String, String> entry : entrySet)
      			{
      				// 设置到请求头到HttpRequestBase对象中
      				httpMethod.setHeader(entry.getKey(), entry.getValue());
      			}
      		}
      	}
      	
      	/**
      	 * Description: 封装请求参数
      	 * 
      	 * @param params
      	 * @param httpMethod
      	 * @throws UnsupportedEncodingException
      	 */
      	public static void packageParam(Map<String, String> params,
      			HttpEntityEnclosingRequestBase httpMethod) throws UnsupportedEncodingException
      	{
      		// 封装请求参数
      		if (params != null)
      		{
      			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
      			Set<Entry<String, String>> entrySet = params.entrySet();
      			for (Entry<String, String> entry : entrySet)
      			{
      				nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
      			}
      			
      			// 设置到请求的http对象中
      			httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));
      		}
      	}
      	
      	/**
      	 * Description: 获得响应结果
      	 * 
      	 * @param httpResponse
      	 * @param httpClient
      	 * @param httpMethod
      	 * @return
      	 * @throws Exception
      	 */
      	private static HttpClientResult getHttpClientResult(CloseableHttpResponse httpResponse,
      			CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws Exception
      	{
      
      		if (httpResponse == null){
      			httpResponse = httpClient.execute(httpMethod);
      		}
      
      
      		// 获取返回结果
      		if (httpResponse != null && httpResponse.getStatusLine() != null)
      		{
      			String content = "";
      			if (httpResponse.getEntity() != null)
      			{
      				content = EntityUtils.toString(httpResponse.getEntity(), ENCODING);
      			}
      			Header[] headers = httpResponse.getAllHeaders();
      			Map<String, String> headerMap = new HashMap<>();
      			for (Header header : headers)
      			{
      				headerMap.put(header.getName(), header.getValue());
      			}
      			return new HttpClientResult(httpResponse.getStatusLine()
      					.getStatusCode(), content, headerMap);
      		}
      		return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
      	}
      	
      	/**
      	 * Description: 释放资源
      	 * 
      	 * @param httpResponse
      	 * @param httpClient
      	 * @throws IOException
      	 */
      	public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient)
      			throws IOException
      	{
      		// 释放资源
      		if (httpResponse != null)
      		{
      			httpResponse.close();
      		}
      		if (httpClient != null)
      		{
      			httpClient.close();
      		}
      	}
      	
      	public static CloseableHttpClient getIgnoeSSLClient() throws Exception
      	{
      		SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy()
      		{
      			@Override
      			public boolean isTrusted(X509Certificate[] x509Certificates, String s)
      					throws CertificateException
      			{
      				return true;
      			}
      			
      		}).build();
      		
      		// 创建httpClient
      		CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext)
      				.setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
      		return client;
      	}
      
      }
      


Springboot -- 用更优雅的方式发HTTP请求(RestTemplate详解) - 简书 (jianshu.com)https://www.jianshu.com/p/27a82c494413

Springboot -- 用更优雅的方式发HTTP请求(RestTemplate详解)_来日可期的博客-CSDN博客https://blog.csdn.net/lairikeqi/article/details/106606144?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2~default~OPENSEARCH~default-1.no_search_link&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2~default~OPENSEARCH~default-1.no_search_link


Spring Boot中,可以使用`RestTemplate`和`WebClient`来发送HTTP请求。这两种方式Spring Boot中的用法与在Spring中基本相同。 1. `RestTemplate`:可以通过在应用程序中注入`RestTemplate`来使用它。Spring Boot会自动配置`RestTemplate`的实例,可以直接使用。以下是一个示例: ```java @RestController public class MyController { private final RestTemplate restTemplate; public MyController(RestTemplate restTemplate) { this.restTemplate = restTemplate; } @GetMapping("/example") public String example() { String url = "http://example.com/api/resource"; ResponseEntity<String> response = restTemplate.getForEntity(url, String.class); String responseBody = response.getBody(); return responseBody; } } ``` 2. `WebClient`:可以通过在应用程序中注入`WebClient.Builder`来创建`WebClient`实例,并使用它发送HTTP请求。以下是一个示例: ```java @RestController public class MyController { private final WebClient.Builder webClientBuilder; public MyController(WebClient.Builder webClientBuilder) { this.webClientBuilder = webClientBuilder; } @GetMapping("/example") public Mono<String> example() { String url = "http://example.com/api/resource"; return webClientBuilder.build().get() .uri(url) .retrieve() .bodyToMono(String.class); } } ``` 需要注意的是,Spring Boot会自动配置`RestTemplate`和`WebClient`的实例,因此无需任何额外的配置。在使用`RestTemplate`时,可以直接注入它,并使用它的方法发送HTTP请求。在使用`WebClient`时,需要通过`WebClient.Builder`创建`WebClient`实例,并使用链式调用的方式来构建和发送请求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值