Http、Https发送Get、Post请求

 (一)方式一:HttpURLConnection

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * 
 * @author shilei
 *
 * @time 2019年11月23日 下午4:10:56
 *
 * @desc Http、Https发送Get、Post请求
 */
public class HttpApi {
	/**
	 * 向指定URL发送GET方法的请求
	 *
	 * @param url   发送请求的URL
	 * @param param 请求参数是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表远程资源的响应结果
	 */
	private static String sendGet(String url, String param, boolean isHttps) {
		if (isHttps)
			setUpHttpsURLConnection();

		StringBuffer result = new StringBuffer();
		BufferedReader in = null;
		try {
			if (ToolValid.isNotEmpty(param))
				url = url + "?" + param;

			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestMethod("GET");// POST GET PUT DELETE
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");

			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line = "";
			while ((line = in.readLine()) != null) {
				result.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (in != null)
					in.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result.toString();
	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 *
	 * @param url   发送请求的 URL
	 * @param param JSON字符串
	 * @return 所代表远程资源的响应结果
	 */
	private static String sendPost(String url, String param, boolean isHttps) {
		if (isHttps)
			setUpHttpsURLConnection();

		PrintWriter out = null;
		BufferedReader in = null;
		StringBuffer result = new StringBuffer();
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestMethod("POST");// POST GET PUT DELETE
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);

			out = new PrintWriter(conn.getOutputStream());
			out.print(param);
			out.flush();

			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line = "";
			while ((line = in.readLine()) != null) {
				result.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null)
					out.close();
				if (in != null)
					in.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result.toString();
	}

	// Http(Post方式)
	public static String sendPost(String url, String param) {
		return sendPost(url, param, false);
	}

	// Http(Get方式)
	public static String sendGet(String url, String param) {
		return sendGet(url, param, false);
	}

	// Https(Get方式)
	public static String sendHttpsGet(String url, String param) {
		return sendGet(url, param, true);
	}

	// Https(Post方式)
	public static String sendHttpsPost(String url, String param) {
		return sendPost(url, param, true);
	}

	/**
	 * 
	 * @desc 设置Https跳过证书验证
	 *
	 */
	private static void setUpHttpsURLConnection() {
		try {
			HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
				@Override
				public boolean verify(String hostname, SSLSession session) {
					return true;
				}
			});
			SSLContext sc = SSLContext.getInstance("TLS");
			sc.init(null, new TrustManager[] { new X509TrustManager() {

				@Override
				public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					// TODO Auto-generated method stub
				}

				@Override
				public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					// TODO Auto-generated method stub
				}

				@Override
				public X509Certificate[] getAcceptedIssuers() {
					// TODO Auto-generated method stub
					return null;
				}

			} }, new SecureRandom());
			HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		}
	}
}

(二)补充,方式二:利用 RestTemplate

package com.***.plan***.config;

import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * RestTemplate远程调用:跳过https验证
 *
 * @author shilei
 * @date 2022-09-20 19:44
 */
@Configuration
public class RestTemplateConfig {

//    @Bean
//    RestTemplate restTemplate() {
//        return new RestTemplate();
//    }

    @Bean
    public RestTemplate restTemplate(HttpComponentsClientHttpRequestFactory httpsFactory) {
        RestTemplate restTemplate = new RestTemplate(httpsFactory);
        restTemplate.setErrorHandler(new ResponseErrorHandler() {
            @Override
            public boolean hasError(ClientHttpResponse clientHttpResponse) {
                return false;
            }

            @Override
            public void handleError(ClientHttpResponse clientHttpResponse) {
            }
        });
        return restTemplate;
    }

    @Bean(name = "httpsFactory")
    public HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory() throws Exception {
        CloseableHttpClient httpClient = acceptsUntrustedCertsHttpClient();
        HttpComponentsClientHttpRequestFactory httpsFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
        httpsFactory.setReadTimeout(3000);
        httpsFactory.setConnectTimeout(3000);
        return httpsFactory;
    }

    public static CloseableHttpClient acceptsUntrustedCertsHttpClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        HttpClientBuilder b = HttpClientBuilder.create();
        // setup a Trust Strategy that allows all certificates.
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();
        b.setSSLContext(sslContext);
        // don't check Host names, either.
        HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
        // create a SSL Socket Factory, to use our weakened "trust strategy"  and create a Registry, to register it.
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory)
                .build();
        // create connection-manager using registry allows multi-threaded use
        PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        connMgr.setMaxTotal(200);
        connMgr.setDefaultMaxPerRoute(100);
        b.setConnectionManager(connMgr);
        return b.build();
    }

}
    @Resource
    private RestTemplate restTemplate;
    // https调用
    HttpEntity<HashMap<String, Object>> requestEntity = new HttpEntity(parameterMap, headers);
    log.info("https调用发送短信接口入参:{}", requestEntity);
    String returnedValue;
    try {
        returnedValue = sendMsgUtil.restTemplate.postForObject(msgConfig.getUrl(), requestEntity, String.class);
    } catch (RestClientException e) {
        log.error("https调用发送短信接口异常信息:{}", e.getCause().toString());
        throw new RuntimeException(e.getCause().toString());
    }
    log.info("https调用发送短信接口出参:{}", returnedValue);

(三)再补充,方式三:利用HttpClient来支持多线程高并发的场景:

import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.UnsupportedEncodingException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.NameValuePair;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

public class Httpclient {

	// 连接池管理器
	private final static PoolingHttpClientConnectionManager poolConnManager = new PoolingHttpClientConnectionManager();

	// retry handler
	private final static HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() {
		public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
			if (executionCount >= 5) {
				return false;
			}
			if (exception instanceof NoHttpResponseException) {
				return true;
			}
			if (exception instanceof InterruptedIOException) {
				return false;
			}
			if (exception instanceof UnknownHostException) {
				return false;
			}
			if (exception instanceof ConnectTimeoutException) {
				return false;
			}
			HttpClientContext clientContext = HttpClientContext.adapt(context);

			HttpRequest request = clientContext.getRequest();

			if (!(request instanceof HttpEntityEnclosingRequest)) {
				return true;
			}
			return false;
		}
	};

	static { // 类加载的时候 设置最大连接数 和 每个路由的最大连接数
		poolConnManager.setMaxTotal(2000);
		poolConnManager.setDefaultMaxPerRoute(1000);
	}

	/**
	 * ########################### core code #######################
	 * 
	 * @return
	 */
	private static CloseableHttpClient getCloseableHttpClient() {
		CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(poolConnManager)
				.setRetryHandler(httpRequestRetryHandler).build();
		return httpClient;
	}

	public static String postRequest(String httpUrl, String jsonStr) {
		CloseableHttpClient httpClient = getCloseableHttpClient();
		HttpPost httpPost = new HttpPost(httpUrl);
		CloseableHttpResponse response = null;
		String responseBody = "";
		try {
//			UrlEncodedFormEntity paramEntity = getFormEntity(jsonStr);
			StringEntity paramEntity = getStringEntity(jsonStr);
			paramEntity.setContentEncoding("utf-8");
			paramEntity.setContentType("application/json");
			httpPost.setEntity(paramEntity);
			response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			if (entity != null)
				responseBody = EntityUtils.toString(entity, "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					EntityUtils.consume(response.getEntity());
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return responseBody;
	}

	/**
	 * @return
	 * @time 2022年7月6日 上午10:27:22
	 * @return UrlEncodedFormEntity
	 * @throws UnsupportedEncodingException
	 * @tags 表单对象提交,注:NameValuePair仅支持参数类型为字符串
	 */
	private static UrlEncodedFormEntity getFormEntity(String jsonStr) throws UnsupportedEncodingException {
		List<NameValuePair> params = new ArrayList<>();
		@SuppressWarnings("unchecked")
		Map<String, Object> args = JSONObject.parseObject(jsonStr, Map.class);
		Set<Entry<String, Object>> entrySet = args.entrySet();
		for (Entry<String, Object> entry : entrySet) {
			params.add(new BasicNameValuePair(entry.getKey(),
					entry.getValue() != null ? String.valueOf(entry.getValue()) : null));
		}
		UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "utf-8");
		return formEntity;
	}

	/**
	 * @return
	 * @time 2022年7月6日 上午10:27:22
	 * @return StringEntity
	 * @throw
	 * @tags json字符串提交
	 */
	private static StringEntity getStringEntity(String jsonStr) {
		StringEntity stringEntity = new StringEntity(jsonStr, "utf-8"); // 解决中文乱码问题
		return stringEntity;
	}

}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值