HTTPClient请求Http接口

本文介绍了一个全面增强的HTTP客户端工具类,该类利用Apache HttpClient实现GET和POST请求,包括处理JSON参数、文件上传和下载等功能。通过自定义SSL策略和连接管理,确保了稳定性和安全性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package awb.aweb_soa.global.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;

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

import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import awb.aweb_soa.global.exception.SOAException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * @author 马弦
 * @date 2017年10月23日 下午2:49 HttpClient工具类
 * 
 * 2018年7月25日14:20:27
 * 重构  加强 
 * 
 */
public class HttpUtil {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(HttpUtil.class);
	private static HttpClient httpClient;
	private static final String CONFIG_FILE_PATH="/httpclient.properties";
	private static final String SSL_VERSION_KEY="https.ssl.version";//
	private static final String TLS_VERSION_KEY="https.tls.version";//TLSv1,TLSv1.1,TLSv1.2
	private static final String CIPHER_SUITES_KEY="https.ciphersuites";//null
	private static final String KEEP_ALIVE_TIME_KEY="http.defaultkeepalivetime";//20000
	
	static {
		try {
			Map<String,String> config=MapBuilder.<String,String>hashMap()
					.map(SSL_VERSION_KEY, "SSLv3")
					.map(TLS_VERSION_KEY, "TLSv1,TLSv1.1,TLSv1.2")
					.map(CIPHER_SUITES_KEY, null)
					.map(KEEP_ALIVE_TIME_KEY, "20000")
					.build();
			try(InputStream in=HttpUtil.class.getResourceAsStream(CONFIG_FILE_PATH)){
				Properties properties=new Properties();
				properties.load(in);
				properties.forEach((key,value)->config.put((String)key, (String)value));
			}catch(Exception e){
				LOGGER.warn("加载HttpClient配置失败",e);
			}
			ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {
			    @Override
			    public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
			        HeaderElementIterator it = new BasicHeaderElementIterator
			            (response.headerIterator(HTTP.CONN_KEEP_ALIVE));
			        while (it.hasNext()) {
			            HeaderElement he = it.nextElement();
			            String param = he.getName();
			            String value = he.getValue();
			            if (value != null && param.equalsIgnoreCase
			               ("timeout")) {
			                return Long.parseLong(value) * 1000;
			            }
			        }
			        return Integer.parseInt(config.get(KEEP_ALIVE_TIME_KEY));//如果没有约定,则默认定义时长为20s
			    }

			};
			SSLContext sslContext = SSLContext.getInstance(config.get(SSL_VERSION_KEY));
			sslContext.init(null, new TrustManager[]{
					new X509TrustManager(){
					@Override
					public void checkClientTrusted(
							X509Certificate[] paramArrayOfX509Certificate,
							String paramString) throws CertificateException {}
	
					@Override
					public void checkServerTrusted(
							X509Certificate[] paramArrayOfX509Certificate,
							String paramString) throws CertificateException {}
	
					@Override
					public X509Certificate[] getAcceptedIssuers() {return null;}
				}
			}, null);
			 // Allow TLSv1 protocol only
	        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
	        		sslContext, 
	        		config.get(TLS_VERSION_KEY).trim().split("[\\ \\r\\n]*,[\\ \\r\\n]*"),
	        		config.get(CIPHER_SUITES_KEY)==null?null:config.get(CIPHER_SUITES_KEY).trim().split("[\\ \\r\\n]*,[\\ \\r\\n]*"), //
	        		(paramString,paramSSLSession)->true
	        	);
			
	        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
	        		RegistryBuilder.<ConnectionSocketFactory>create()  
		                .register("http", PlainConnectionSocketFactory.INSTANCE)  
		                .register("https",sslSocketFactory)  
		                .build());
			connectionManager.setMaxTotal(500);
			connectionManager.setDefaultMaxPerRoute(50);//例如默认每路由最高50并发,具体依据业务来定
			connectionManager.setValidateAfterInactivity(60000);
			httpClient = HttpClients.custom()
	                .setConnectionManager(connectionManager)
	                .setKeepAliveStrategy(myStrategy)
	                .build();
		} catch (Exception e) {
			throw new IllegalStateException(e.getMessage(),e);
		}
       
	}
	/**
	 * get请求
	 * 
	 * @return
	 */
	public static String doGet(String url) {
		try {
			HttpClient client = httpClient;
			// 发送get请求
			HttpGet request = new HttpGet(url);
			HttpResponse response = client.execute(request);

			/** 请求发送成功,并得到响应 **/
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				/** 读取服务器返回过来的json字符串数据 **/
				String strResult = EntityUtils.toString(response.getEntity());
				return strResult;
			}
		} catch (IOException e) {
			throw new IllegalStateException("GET 接口调用失败 URL:"+url+" "+e.getMessage(),e);
		}

		return null;
	}

	/**
	 * post请求(用于key-value格式的参数)
	 * 
	 * @param url
	 * @param params
	 * @return
	 * @throws IOException
	 * @throws URISyntaxException
	 */
	public static String doPost(String url, Map params) throws IOException,
			URISyntaxException {
		String errorMsg;
		BufferedReader in = null;
		// 定义HttpClient
		HttpClient client = httpClient;
		// 实例化HTTP方法
		HttpPost request = new HttpPost();
		request.setURI(new URI(url));

		// 设置参数
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String value = String.valueOf(params.get(name));
			nvps.add(new BasicNameValuePair(name, value));
		}
		request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

		HttpResponse response = client.execute(request);
		int code = response.getStatusLine().getStatusCode();
		if (code == 200) { // 请求成功
			in = new BufferedReader(new InputStreamReader(response.getEntity()
					.getContent(), "utf-8"));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}

			in.close();
			JSONObject resMap = JSON.parseObject(sb.toString());
			if (resMap == null) {
				return "";
			}
			if (resMap.get("errorMsg") == null) {

				return sb.toString();
			} else {
				errorMsg = JSON.parseObject(sb.toString()).get("errorMsg")
						.toString();
				if (errorMsg != null && !errorMsg.equals(""))
					throw SOAException.error("SA6102", errorMsg);
				return sb.toString();
			}
		} else { //
			throw SOAException.error("SA6102", "状态码:" + code);
		}
	}

	/**
	 * post请求(用于key-value格式的参数)
	 * 
	 * @param url
	 * @param params
	 * @return
	 * @throws IOException
	 * @throws URISyntaxException
	 */
	public static String doPost2(String url, Map<String, String> params) {
		List<NameValuePair> nvps = params
				.entrySet()
				.stream()
				.map(entry -> new BasicNameValuePair(entry.getKey(), entry
						.getValue())).collect(Collectors.toList());
		// 实例化HTTP方法
		HttpPost request;
		try {
			request = new HttpPost(new URI(url));
		} catch (URISyntaxException e1) {
			throw new RuntimeException("http配置错误", e1);
		}
		// 设置参数
		request.setEntity(new UrlEncodedFormEntity(nvps, Charset
				.forName("UTF-8")));
		// 定义HttpClient
		try  {
			HttpResponse response = httpClient.execute(request);
			int code = response.getStatusLine().getStatusCode();
			String responseString = EntityUtils.toString(response.getEntity(),
					Charset.forName("UTF-8"));
			if (HttpStatus.SC_OK == code) { // 请求成功
				return responseString;
			} else { //
				LOGGER.error("HTTP:" + code);
				LOGGER.error(responseString);
				throw new IllegalStateException("Http接口调用失败,URL:" + url
						+ ", 状态码:" + code);
			}
		} catch (Exception e) {
			throw new IllegalStateException("Http接口调用失败," + e.getMessage(), e);
		}
	}

	/**
	 * post请求(用于请求json格式的参数)
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	public static String doPost(String url, String params) throws Exception {

		HttpPost httpPost = new HttpPost(url);// 创建httpPost
		httpPost.setHeader("Accept", "application/json");
		httpPost.setHeader("Content-Type", "application/json");
		String charSet = "UTF-8";
		StringEntity entity = new StringEntity(params, charSet);
		httpPost.setEntity(entity);
		HttpResponse response = null;

		try {
			response = httpClient.execute(httpPost);
			StatusLine status = response.getStatusLine();
			int state = status.getStatusCode();
			if (state == HttpStatus.SC_OK) {
				HttpEntity responseEntity = response.getEntity();
				String jsonString = EntityUtils.toString(responseEntity);
				return jsonString;
			}
		} catch(Exception e){
			throw new IllegalStateException("接口调用失败,URL:"+url+" " +e.getMessage(),e);
		}
		return null;
	}
	/**
	 * post请求文件(用于key-value格式的参数)
	 * 
	 * @param url
	 * @param params
	 * @param name 文件参数名称
	 * @param file 文件路径
	 * 
	 * @return
	 * @throws IOException
	 * @throws URISyntaxException
	 */
	public static String doPostFile(String url, Map<String, String> params,String name,Path file) {
		
		Assert.isTrue(Files.exists(file)&&Files.isRegularFile(file), "file 参数不正确 "+file);
		
		// 实例化HTTP方法
		HttpPost request;
		try {
			request = new HttpPost(new URI(url));
		} catch (URISyntaxException e1) {
			throw new RuntimeException("http配置错误", e1);
		}
		try(InputStream stream=Files.newInputStream(file)){
			MultipartEntityBuilder entityBuilder=MultipartEntityBuilder.create()
					.addBinaryBody(name, stream,ContentType.DEFAULT_BINARY,file.getFileName().toString());
			entityBuilder.setCharset(Charset.forName("UTF-8"));
			ContentType contentType=ContentType.create("text/plain",  Charset
					.forName("UTF-8"));
			params.forEach((key,value)->{
				entityBuilder.addTextBody(key, value, contentType);
			});
			// 设置参数
			request.setEntity(entityBuilder.build());
			// 定义HttpClient
			HttpResponse response = httpClient.execute(request);
			int code = response.getStatusLine().getStatusCode();
			String responseString = EntityUtils.toString(response.getEntity(),
					Charset.forName("UTF-8"));
			if (HttpStatus.SC_OK == code) { // 请求成功
				return responseString;
			} else { //
				LOGGER.error("HTTP:" + code);
				LOGGER.error(responseString);
				throw new IllegalStateException("Http接口调用失败,URL:" + url
						+ ", 状态码:" + code);
			}
		} catch (Exception e) {
			throw new IllegalStateException("Http接口调用失败," + e.getMessage(), e);
		}
	}
	public static void doDownloadFile(String url, Map<String, String> params,OutputStream out){
		List<NameValuePair> nvps = params
				.entrySet()
				.stream()
				.map(entry -> new BasicNameValuePair(entry.getKey(), entry
						.getValue())).collect(Collectors.toList());
		// 实例化HTTP方法
		HttpPost request;
		try {
			request = new HttpPost(new URI(url));
		} catch (URISyntaxException e1) {
			throw new RuntimeException("http配置错误", e1);
		}
		// 设置参数
		request.setEntity(new UrlEncodedFormEntity(nvps, Charset
				.forName("UTF-8")));
		// 定义HttpClient
		try {
			HttpResponse response = httpClient.execute(request);
			int code = response.getStatusLine().getStatusCode();
			if (HttpStatus.SC_OK == code) { // 请求成功
				response.getEntity().writeTo(out);
			} else { //
				LOGGER.error("HTTP:" + code);
				String responseString = EntityUtils.toString(response.getEntity(),
						Charset.forName("UTF-8"));
				LOGGER.error(responseString);
				throw new IllegalStateException("Http接口调用失败,URL:" + url
						+ ", 状态码:" + code);
			}
		} catch (Exception e) {
			throw new IllegalStateException("Http接口调用失败," + e.getMessage(), e);
		}
	}
	
	public static void main(String[] args) {
		System.out.println(doPost2("https://localhost:8443/",Collections.emptyMap()));
//		System.out.println(Arrays.asList("  123   ,   2333, \n 333\n, 444 ".trim().split("[\\ \\r\\n]*,[\\ \\r\\n]*")));
	}
}

 

好的,以下是使用Apache HttpClient请求POST接口的示例代码: ```java import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpClientExample { public static void main(String[] args) { HttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://example.com/api"); // 设置请求httpPost.setHeader("Content-Type", "application/json"); // 设置请求体 String requestBody = "{\"name\":\"John\",\"age\":30}"; StringEntity entity = new StringEntity(requestBody, StandardCharsets.UTF_8); httpPost.setEntity(entity); try { HttpResponse response = httpClient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); String responseString = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8); System.out.println("Response: " + responseString); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` 在上面的示例中,我们创建了一个默认的HttpClient实例,然后构造了一个HttpPost请求对象,设置了请求头和请求体,最后发送请求并获取响应。你只需要将请求地址和请求体替换成你的实际接口地址和请求参数即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SenKnight

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值