Java使用HTTPClient发起HTTP或HTTPS请求

本文介绍了如何在Java中用httpclient发起http或https(跳过验证)请求,废话不多说,上代码。

1、导入httpclient的pom依赖

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.2</version>
</dependency>

2、通用请求代码

package com.test.center.common.utils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
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.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.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;

public class HttpClientUtil {

	private final static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

	private static CloseableHttpClient client;

	static {
		try {
			// 采用绕过验证的方式处理https请求
			SSLContext sslcontext = createIgnoreVerifySSL();
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
					NoopHostnameVerifier.INSTANCE);
			// 设置协议http和https对应的处理socket链接工厂的对象
			Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
					.register("http", PlainConnectionSocketFactory.INSTANCE).register("https", sslsf).build();
			PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
					socketFactoryRegistry);
			HttpClients.custom().setConnectionManager(connManager);
			// 创建自定义的httpclient对象
			client = HttpClients.custom().setConnectionManager(connManager).setSSLSocketFactory(sslsf).build();
		} catch (KeyManagementException | NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

	}
	

	/**
	 * 发送https请求
	 * 
	 * @param url
	 *            请求地址
	 * @param param
	 *            参数
	 * @param method
	 *            请求的方法类型
	 * @param authorization
	 *            授权用户名及密码的编码
	 * @return 响应信息
	 */
	public static String sendHttpsRequest(String url, String param, String method, String authorization) {
		method = method.toUpperCase();
		switch (method) {
		case "GET":
			HttpGet get = new HttpGet(url);
			return JSON.toJSONString(execute(get, authorization));
		case "POST":
			HttpPost post = new HttpPost(url);
			// 判断是否有参数
			if (!StringUtils.isEmpty(param)) {
				// 构建消息实体
				StringEntity message = new StringEntity(param, Charset.forName("UTF-8"));
				message.setContentEncoding("UTF-8");
				// 发送Json格式的数据请求
				message.setContentType("application/json");
				post.setEntity(message);
			}
			return JSON.toJSONString(execute(post, authorization));
		case "PUT":
			HttpPut put = new HttpPut(url);
			// 判断是否有参数
			if (!StringUtils.isEmpty(param)) {
				// 构建消息实体
				StringEntity message = new StringEntity(param, Charset.forName("UTF-8"));
				message.setContentEncoding("UTF-8");
				// 发送Json格式的数据请求
				message.setContentType("application/json");
				put.setEntity(message);
			}
			return JSON.toJSONString(execute(put, authorization));
		case "PATCH":
			HttpPatch patch = new HttpPatch(url);
			// 判断是否有参数
			if (!StringUtils.isEmpty(param)) {
				// 构建消息实体
				StringEntity message = new StringEntity(param, Charset.forName("UTF-8"));
				message.setContentEncoding("UTF-8");
				// 发送Json格式的数据请求
				message.setContentType("application/json");
				patch.setEntity(message);
			}
			return JSON.toJSONString(execute(patch, authorization));
		case "DELETE":
			HttpDelete delete = new HttpDelete(url);
			return JSON.toJSONString(execute(delete, authorization));
		default:
			Map<String, String> resultMap = new HashMap<>();
			resultMap.put("status", "failure");
			resultMap.put("message", "暂不支持的方法类型");
			resultMap.put("result", "");
			return JSON.toJSONString(resultMap);
		}
	}

	/**
	 * 发送请求
	 * 
	 * @param request
	 *            http请求类型
	 * @param authorization
	 * @return 结果集
	 */
	private static Map<String, String> execute(HttpUriRequest request, String authorization) {
		Map<String, String> resultMap = new HashMap<>();
		CloseableHttpResponse response = null;
		HttpEntity entity = null;
		String result = "";
		try {
			// 指定报文头Content-type、Authorization
			request.setHeader("Content-type", "application/json");
			request.setHeader("Authorization", "Basic " + authorization);
			response = client.execute(request);
			// 获取结果实体
			if (response != null) {
				entity = response.getEntity();
				result = EntityUtils.toString(entity, "UTF-8");
				if (response.getStatusLine().getStatusCode() == 200) {
					resultMap.put("status", "success");
					resultMap.put("message", "");
					resultMap.put("result", result);
				} else {
					resultMap.put("status", "failure");
					resultMap.put("message", result);
					resultMap.put("result", "");
				}
			} else {
				logger.error("发送https请求异常,响应信息为空");
				resultMap.put("status", "failure");
				resultMap.put("message", "发送https请求异常,响应信息为空");
				resultMap.put("result", "");
			}
		} catch (ParseException | IOException e) {
			logger.error("以POST方法发送https请求失败", e);
			resultMap.put("status", "failure");
			resultMap.put("message", e.getMessage());
			resultMap.put("result", "");
		} finally {
			try {
				EntityUtils.consume(entity);  
				//释放链接  
				if(response!=null){
					response.close();
				}
			} catch (IOException e) {
				logger.error("资源关闭异常",e);
			}
		}
		return resultMap;
	}

	/**
	 * 绕过验证
	 * 
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws KeyManagementException
	 */
	private static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
		SSLContext sc = SSLContext.getInstance("SSLv3");

		// 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
		X509TrustManager trustManager = new X509TrustManager() {
			@Override
			public void checkClientTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
					String paramString) throws CertificateException {
			}

			@Override
			public void checkServerTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
					String paramString) throws CertificateException {
			}

			@Override
			public java.security.cert.X509Certificate[] getAcceptedIssuers() {
				return null;
			}
		};

		sc.init(null, new TrustManager[] { trustManager }, null);
		return sc;
	}

}

实际生产中使用的通用代码,导入jar包即可使用。

使用Java HttpClient发起请求,你可以按照以下步骤进行操作: 1. 首先,创建一个HttpPost对象,将请求的URL作为参数传递给它。可以使用引用中的示例代码中的以下行完成此步骤: ``` HttpPost httpPost = new HttpPost(url); ``` 2. 接下来,创建一个CloseableHttpClient对象,可以使用引用中的示例代码中的以下行完成此步骤: ``` CloseableHttpClient httpClient = HttpClientBuilder.create().build(); ``` 3. 设置请求的数据格式和内容。你可以使用StringEntity类创建一个包含请求数据的实体。可以使用引用中的示例代码中的以下行完成此步骤: ``` StringEntity entity = new StringEntity(jsonData, "utf-8"); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); httpPost.setEntity(entity); ``` 4. 执行POST请求并获取响应结果。可以使用httpClient的execute方法来执行请求,并使用HttpResponse对象接收响应结果。你可以根据需要使用不同的方法来处理响应结果。例如,可以使用BasicResponseHandler类的实例来处理响应结果字符串。可以使用引用中的示例代码中的以下行完成此步骤: ``` BasicResponseHandler handler = new BasicResponseHandler(); result = httpClient.execute(httpPost, handler); ``` 5. 最后,记得释放连接。可以使用httpClient的close方法来关闭连接。可以使用引用中的示例代码中的以下行完成此步骤: ``` httpClient.close(); ``` 综上所述,以上步骤提供了一个示例的Java HttpClient发起请求的过程。根据你的需求,你还可以根据具体的情况进行适当的调整和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值