HTTPClient使用

Apache httpclient 使用

依赖

版本 4.5.13

<!-- httpclient -->
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
		</dependency>
		<!-- HTTPclient上传文件 -->
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpmime</artifactId>
		</dependency>
代码
package com.conformity.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
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.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;

/**
 * @author Admin
 *
 */
public class HttpClientUtils {
	/** get请求  相当于postman get请求  通过params传递参数
	 * @param url
	 * @param param
	 * @return
	 */
	public static String getUrlWithParam(String url,Map<String, String> param) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		HttpGet get = null;
		String result = "";
		StringBuilder sb = new StringBuilder();
		RequestConfig config = RequestConfig.custom()
		.setConnectTimeout(5000) //连接超时 单位毫秒
		.setSocketTimeout(5000) //读取数据超时 单位毫秒
		.setConnectionRequestTimeout(5000) //从连接池获取connection的超时时间
		.build();
		try {
			if (param != null && param.size() > 0) {
				Set<String> keySet = param.keySet();
				for (String key : keySet) {
					String p = URLEncoder.encode(param.get(key),StandardCharsets.UTF_8.name());
					sb.append(key+"="+p);
					sb.append("&");
				}
				sb.deleteCharAt(sb.lastIndexOf("&"));
				get = new HttpGet(url+"?"+sb.toString());
				System.out.println(url+"?"+sb.toString());
			}else {
				get = new HttpGet(url);
			}
			get.setConfig(config);
			response = httpClient.execute(get);
			//本次请求是否成功
			if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
				System.out.println("请求成功");
				//获取响应头
				Header[] allHeaders = response.getAllHeaders();
				for (Header header : allHeaders) {
					System.out.println("响应头---"+header.getName()+":"+header.getValue());
				}
			}else {
				System.out.println("请求失败:"+response.getStatusLine().getStatusCode());
			}

			//HttpEntity 不仅可以作为请求的结果 ,也可以作为请求参数  有很多的实现
			HttpEntity entity = response.getEntity();
			//获取响应类型
			System.out.println("ContentType:"+entity.getContentType());
			result = EntityUtils.toString(entity,StandardCharsets.UTF_8);
			//确认流被关闭
			EntityUtils.consume(entity);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if (httpClient != null) {
				try {
					httpClient.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	/**post表单请求    相当于postman 的表单上传 body中的application/x-www-form-urlencoded
	 * @param url
	 * @param map
	 * @return
	 */
	public static String postForm (String url,Map<String,Object> map) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		HttpPost httpPost = null;
		String result = "";
		RequestConfig config = RequestConfig.custom()
		.setProxy(new HttpHost("代理地址", 80))
		.setConnectTimeout(5000) //连接超时 单位毫秒
		.setSocketTimeout(5000) //读取数据超时 单位毫秒
		.setConnectionRequestTimeout(5000) //从连接池获取connection的超时时间
		.build();
		try {
			httpPost = new HttpPost(url);
			//不设置时post请求默认就是这个
			httpPost.addHeader("ContentType", "application/x-www-form-urlencoded; charset=UTF-8");
			//post设置参数
			if (map != null && map.size() > 0) {
				List< NameValuePair> list = new ArrayList<>();
				Set<String> keySet = map.keySet();
				for (String key : keySet) {
					list.add(new BasicNameValuePair(key, map.get(key).toString()));
				}
				httpPost.setEntity(new UrlEncodedFormEntity(list,StandardCharsets.UTF_8));
			}
			httpPost.setConfig(config);
			response = httpClient.execute(httpPost);
			//本次请求是否成功
			if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
				System.out.println("请求成功");
				//获取响应头
				Header[] allHeaders = response.getAllHeaders();
				for (Header header : allHeaders) {
					System.out.println("响应头---"+header.getName()+":"+header.getValue());
				}
			}else {
				System.out.println("请求失败:"+response.getStatusLine().getStatusCode());
			}

			//HttpEntity 不仅可以作为请求的结果 ,也可以作为请求参数  有很多的实现
			HttpEntity entity = response.getEntity();
			//获取响应类型
			System.out.println("ContentType:"+entity.getContentType());
			result = EntityUtils.toString(entity,StandardCharsets.UTF_8);
			//确认流被关闭
			EntityUtils.consume(entity);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if (httpClient != null) {
				try {
					httpClient.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	/** post请求 json数据  相当于postman body中的form-data
	 * @param url
	 * @param map
	 * @return
	 */
	public static String postMap(String url,Map<String, Object> map) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		HttpPost httpPost = null;
		String result = "";
		RequestConfig config = RequestConfig.custom()
		.setConnectTimeout(5000) //连接超时 单位毫秒
		.setSocketTimeout(5000) //读取数据超时 单位毫秒
		.setConnectionRequestTimeout(5000) //从连接池获取connection的超时时间
		.build();
		try {
			httpPost = new HttpPost(url);
			httpPost.addHeader("ContentType", "application/json; charset=UTF-8");
			if (map != null && map.size() > 0) {
				List<BasicNameValuePair> list = new ArrayList<>();
				Set<String> keySet = map.keySet();
				for (String key : keySet) {
					BasicNameValuePair base = new BasicNameValuePair(key, map.get(key).toString());
					list.add(base);
				}
				httpPost.setEntity(new UrlEncodedFormEntity(list, StandardCharsets.UTF_8.name()));
			}
			httpPost.setConfig(config);
			response = httpClient.execute(httpPost);
			//本次请求是否成功
			if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
				System.out.println("请求成功");
				//获取响应头
				Header[] allHeaders = response.getAllHeaders();
				for (Header header : allHeaders) {
					System.out.println("响应头---"+header.getName()+":"+header.getValue());
				}
			}else {
				System.out.println("请求失败:"+response.getStatusLine().getStatusCode());
			}

			//HttpEntity 不仅可以作为请求的结果 ,也可以作为请求参数  有很多的实现
			HttpEntity entity = response.getEntity();
			//获取响应类型
			System.out.println("ContentType:"+entity.getContentType());
			result = EntityUtils.toString(entity,StandardCharsets.UTF_8);
			//确认流被关闭
			EntityUtils.consume(entity);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if (httpClient != null) {
				try {
					httpClient.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return result;


	}

	/**post请求 json数据 相当于postman body 中的raw  json格式
	 * @param url
	 * @param params
	 * @return
	 */
	public static String postJson(String url, JSONObject params) {

		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		HttpPost httpPost = null;
		String result = "";
		RequestConfig config = RequestConfig.custom()
		.setConnectTimeout(5000) //连接超时 单位毫秒
		.setSocketTimeout(5000) //读取数据超时 单位毫秒
		.setConnectionRequestTimeout(5000) //从连接池获取connection的超时时间
		.build();
		try {
			httpPost = new HttpPost(url);
			if (params != null && params.size() > 0) {
				//设置请求类型为json
				httpPost.addHeader("ContentType", "application/json; charset=UTF-8");
				StringEntity jsonEntity = new StringEntity(params.toJSONString(), Consts.UTF_8);
				//给参数实体设置内容类型
				jsonEntity.setContentType("application/json; charset=UTF-8");
				//设置编码类型 防止乱码
				jsonEntity.setContentEncoding(Consts.UTF_8.name());
				httpPost.setEntity(jsonEntity);
			}
			httpPost.setConfig(config);
			response = httpClient.execute(httpPost);
			//本次请求是否成功
			if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
				System.out.println("请求成功");
				//获取响应头
				Header[] allHeaders = response.getAllHeaders();
				for (Header header : allHeaders) {
					System.out.println("响应头---"+header.getName()+":"+header.getValue());
				}
			}else {
				System.out.println("请求失败:"+response.getStatusLine().getStatusCode());
			}

			//HttpEntity 不仅可以作为请求的结果 ,也可以作为请求参数  有很多的实现
			HttpEntity entity = response.getEntity();
			//获取响应类型
			System.out.println("ContentType:"+entity.getContentType());
			result = EntityUtils.toString(entity,StandardCharsets.UTF_8);
			//确认流被关闭
			EntityUtils.consume(entity);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if (httpClient != null) {
				try {
					httpClient.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return result;

	}

/**post请求 绕过https安全认证
	 * @param url
	 * @param params
	 * @return
	 */
	public static String postJsonSSL(String url, JSONObject params) {
		Registry<ConnectionSocketFactory> registry = null;
		try {
			//获取注册中心   注册协议
			registry = RegistryBuilder.<ConnectionSocketFactory>create().
					register("http", PlainConnectionSocketFactory.INSTANCE).
					register("https", TrustCertificate()).
					build();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		//创建HTTPclient连接池
		PoolingHttpClientConnectionManager pool = new PoolingHttpClientConnectionManager(registry);
		//传入连接池 创建 HttpClientBuilder
		HttpClientBuilder builder = HttpClients.custom().setConnectionManager(pool);
		//通过HttpClientBuilder创建CloseableHttpClient
		CloseableHttpClient httpClient = builder.build();
		CloseableHttpResponse response = null;
		HttpPost httpPost = null;
		String result = "";
		RequestConfig config = RequestConfig.custom()
		.setConnectTimeout(40000) //连接超时 单位毫秒
		.setSocketTimeout(40000) //读取数据超时 单位毫秒
		.setConnectionRequestTimeout(40000) //从连接池获取connection的超时时间
		.build();
		try {
			httpPost = new HttpPost(url);
			if (params != null && params.size() > 0) {
				//设置请求类型为json
				httpPost.addHeader("ContentType", "application/json; charset=UTF-8");
				StringEntity jsonEntity = new StringEntity(params.toJSONString(), Consts.UTF_8);
				//给参数实体设置内容类型
				jsonEntity.setContentType("application/json; charset=UTF-8");
				//设置编码类型 防止乱码   这里不能设置 会报错
//				jsonEntity.setContentEncoding(Consts.UTF_8.name());
				httpPost.setEntity(jsonEntity);
			}
			httpPost.setConfig(config);
			response = httpClient.execute(httpPost);
			//本次请求是否成功
			if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
				//HttpEntity 不仅可以作为请求的结果 ,也可以作为请求参数  有很多的实现
				HttpEntity entity = response.getEntity();
				//获取响应类型
				System.out.println("ContentType:"+entity.getContentType());
				result = EntityUtils.toString(entity,StandardCharsets.UTF_8);
				//确认流被关闭
				EntityUtils.consume(entity);
				return result;
			}else {
				result = "";
				return result;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if (httpClient != null) {
				try {
					httpClient.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return result;

	}

	@SuppressWarnings("deprecation")
	private static ConnectionSocketFactory TrustCertificate() throws Exception{
		SSLContextBuilder builder = new SSLContextBuilder();
		builder.loadTrustMaterial(null, new TrustStrategy() {
			@Override
			public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
				// TODO Auto-generated method stub
				return true;
			}
		});
		
		SSLContext sslContext = builder.build();
		SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
				sslContext,
				new String[] {"SSLv2Hello","SSLv3","TLSv1","TLSv1.1","TLSv1.2"},
				null,NoopHostnameVerifier.INSTANCE);
		
		return sslConnectionSocketFactory;
	}


	/** 下载图片
	 * @param url  图片路径
	 * @param path 存储路径
	 * @return
	 */
	public static boolean getFile(String url,String path) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		OutputStream os = null;
		HttpGet get = null;
		RequestConfig config = RequestConfig.custom()
		.setConnectTimeout(5000) //连接超时 单位毫秒
		.setSocketTimeout(5000) //读取数据超时 单位毫秒
		.setConnectionRequestTimeout(5000) //从连接池获取connection的超时时间
		.build();
		try {
			get = new HttpGet(url);
			response = httpClient.execute(get);
			//本次请求是否成功
			if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
				System.out.println("请求成功");
			}else {
				System.out.println("请求失败:"+response.getStatusLine().getStatusCode());
				return false;
			}
			get.setConfig(config);
			//HttpEntity 不仅可以作为请求的结果 ,也可以作为请求参数  有很多的实现
			HttpEntity entity = response.getEntity();
			//获取响应类型
			// image/jpg  image/jpeg  image/png  image/图片的后缀
			String contentType = entity.getContentType().getValue();
			String suffix = ".jpg";
			if (contentType.contains("jpg") || contentType.contains("jpeg")) {
				suffix = ".jpg";
			}else if(contentType.contains("png")) {
				suffix = ".png";
			}else if (contentType.contains("bmp") || contentType.contains("bitmap")) {
				suffix = ".bmp";
			}else if (contentType.contains("gif")) {
				suffix = ".gif";
			}

			//获取文件字节流
			String uuid = IdUtil.simpleUUID();
			byte[] byteArray = EntityUtils.toByteArray(entity);
			os = new FileOutputStream(new File(path+File.separator+uuid+suffix));
			os.write(byteArray);
			os.flush();
			//确认流被关闭
			EntityUtils.consume(entity);

			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}finally {
			if (httpClient != null) {
				try {
					httpClient.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	/** 上传图片 相当于postman的表单提交数据
	 * @param url  
	 * @param inputStream
	 * @param params
	 * @return
	 */
	public static String postFile(String url,File[] files,Map<String, String> params) {
		String result = "";
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		HttpPost httpPost = null;
		RequestConfig config = RequestConfig.custom()
		.setConnectTimeout(5000) //连接超时 单位毫秒
		.setSocketTimeout(5000) //读取数据超时 单位毫秒
		.setConnectionRequestTimeout(5000) //从连接池获取connection的超时时间
		.build();
		try {
			httpPost = new HttpPost(url);
			httpPost.setConfig(config);
			MultipartEntityBuilder builder = MultipartEntityBuilder.create();
			//设置内容格式
			builder.setContentType(ContentType.MULTIPART_FORM_DATA);
			//设置字符集编码
			builder.setCharset(StandardCharsets.UTF_8);
			//设置浏览器模式
			builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
			//通过流获取文件
			if (files != null && files.length > 0) {
				for (int i = 0; i < files.length; i++) {
					builder.addBinaryBody("files", files[i]);
				}
			}
			
			//设置普通文本参数  含有中文时不推荐使用  可能会乱码
//			builder.addTextBody("phone", "111111111", ContentType.TEXT_PLAIN);
			if (MapUtil.isNotEmpty(params)) {
				Set<String> keySet = params.keySet();
				for (String key : keySet) {
					//设置中文参数时  使用这个 
					builder.addPart(key, new StringBody(params.get(key),ContentType.create("text/plain", StandardCharsets.UTF_8)));
				}
			}
			HttpEntity entity = builder.build();
			httpPost.setEntity(entity);
			response = httpClient.execute(httpPost);
			if (response.getStatusLine().getStatusCode() == 200) {
				System.out.println("接口成功发送");
			}else {
				return "接口发送失败";
			}
			result = EntityUtils.toString(response.getEntity());
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			result = "系统异常";
			return result;
		}finally {
			if (httpClient != null) {
				try {
					httpClient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
HttpClient 是一个开源的 HTTP 客户端库,用于发送 HTTP 请求和接收 HTTP 响应。它提供了简化的 API,使得进行 HTTP 通信变得更加容易。 要使用 HttpClient,首先需要在项目中引入 HttpClient 的依赖。具体的操作方式取决于你使用的开发环境和构建工具。一般来说,如果是使用 Maven 进行项目管理,可以在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> ``` 如果是使用 Gradle 进行项目管理,可以在 build.gradle 文件中添加以下依赖: ```groovy implementation 'org.apache.httpcomponents:httpclient:4.5.13' ``` 接下来就可以在代码中使用 HttpClient 来发送 HTTP 请求了。下面是一个简单的示例: ```java import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; public class HttpClientExample { public static void main(String[] args) throws Exception { HttpClient httpClient = HttpClientBuilder.create().build(); HttpGet request = new HttpGet("http://example.com"); HttpResponse response = httpClient.execute(request); System.out.println("Response Code: " + response.getStatusLine().getStatusCode()); } } ``` 上述示例中,我们创建了一个 HttpClient 实例,并使用该实例发送了一个 GET 请求到 "http://example.com"。获取到的响应存储在 HttpResponse 对象中,我们可以通过调用 `getStatusCode()` 方法获取响应的状态码。 当然,HttpClient 还提供了丰富的 API,可以进行更加复杂的 HTTP 请求和处理。你可以参考 HttpClient 的官方文档来了解更多详细的使用方法和示例。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值