我是靠谱客的博主 内向云朵,最近开发中收集的这篇文章主要介绍HttpClient 发送 Http 请求工具类,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

导入的依赖:

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

实体类 ShareResult:

public class ShareResult {

	private Integer code;
	private String detail;

	public Integer getCode() {
		return code;
	}

	public void setCode(Integer code) {
		this.code = code;
	}

	public String getDetail() {
		return detail;
	}

	public void setDetail(String detail) {
		this.detail = detail;
	}
}


具体的工具类:


public class HttpUtil {

	private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);

	/**
	 * 用来向指定 uri 发送 post 请求,
	 * @param uri 地址
	 * @return 相应的数据
	 */
	public static ShareResult post(String uri) {
		CloseableHttpResponse response = null;
		HttpPost httpPost = new HttpPost(uri);
		CloseableHttpClient httpClient = HttpClients.createDefault();
		try{
			// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
			// httpClient = HttpClientBuilder.create().build();
			// 请求头
			httpPost.setHeader("Content-Type", "application/json;charset=utf8");
			// 响应模型
			log.info("{}发送请求",uri);
			response = httpClient.execute(httpPost);
			if (response != null) {
				// 从响应模型中获取响应实体
				HttpEntity responseEntity = response.getEntity();
				// log.info("{}返回响应,响应数据{}",uri,JSON.toJSONString(EntityUtils.toString(responseEntity)));
				String result = EntityUtils.toString(responseEntity);
				StatusLine responseStatus = response.getStatusLine();
				ShareResult shareResult = new ShareResult();
				shareResult.setCode(responseStatus.getStatusCode());
				shareResult.setDetail(result);
				return shareResult;
			}
			return null;
		} catch (Exception e) {
			log.error("向{}发送POST请求出错 {}",uri,e);
		}finally {
			try {
				if(httpClient != null) {
					httpClient.close();
				}
				if(response != null){
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 向指定 uri 发送 post 请求,发送 json 格式的数据
	 * @param uri 请求的地址
	 * @param json 要发送的数据
	 */
	public static String post(String uri, String json) {
		HttpPost httpPost = new HttpPost();
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		try{
			// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
			httpClient = HttpClientBuilder.create().build();
			httpPost.setURI(new URI(uri));
			// 将user对象转换为json字符串,并放入entity中
			StringEntity entity = new StringEntity(json, "UTF-8");

			// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
			httpPost.setEntity(entity);
			// 请求头
			httpPost.setHeader("Content-Type", "application/json;charset=utf8");
			// 响应模型
			log.info("{}发送请求,请求数据{}",uri,json);
			response = httpClient.execute(httpPost);
			// 从响应模型中获取响应实体
			HttpEntity responseEntity = response.getEntity();
			log.info("{}返回响应,响应数据{}",uri,JSON.toJSONString(EntityUtils.toString(responseEntity)));
		} catch (Exception e) {
			log.error("发送POST请求出错 {}",uri,e);
		}finally {
			try {
				if(httpClient != null) {
					httpClient.close();
				}
				if(response != null){
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 向指定 uri 发送 post 请求,发送 formdata 数据
	 * @param uri 地址
	 * @param access_token 此处为微博认证的 token
	 * @param content 微博的内容
	 * @param pic 图片地址
	 * readme:参数自己定义,改代码中的 addPart 部分即可   
	 * @return 返回的结果
	 */
	public static ShareResult postForm(String uri, String access_token, String content, File pic) {
		HttpPost httpPost = new HttpPost();
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		try {
			// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
			httpClient = HttpClientBuilder.create().build();
			httpPost.setURI(new URI(uri));
			// 将user对象转换为json字符串,并放入entity中
			FileBody bin = new FileBody(pic);

			StringBody token = new StringBody(access_token, ContentType.TEXT_PLAIN);
			StringBody status = new StringBody(content, ContentType.TEXT_PLAIN);

			HttpEntity entity = MultipartEntityBuilder.create()
					.addPart("pic", bin)
					.addPart("status", status)
					.addPart("access_token", token)
					.build();
			// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
			httpPost.setEntity(entity);
			// 响应模型
			response = httpClient.execute(httpPost);
			// 从响应模型中获取响应实体
			HttpEntity responseEntity = response.getEntity();
			StatusLine responseStatus = response.getStatusLine();
			String entityString = EntityUtils.toString(responseEntity);
			ShareResult result = new ShareResult();
			result.setCode(responseStatus.getStatusCode());
			result.setDetail(entityString);
			log.info("{}返回响应{},响应数据{}", uri,responseStatus, entityString);
			return result;
		} catch (Exception e) {
			log.error("发送POST请求出错 {}", uri, e);
		} finally {
			try {
				if (httpClient != null) {
					httpClient.close();
				}
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 向指定 uri 发送 get 请求
	 * @param uri 指定的 uri
	 * @return 结果
	 */
	public static ShareResult get(String uri) {
		// 创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// 创建http GET请求
		HttpGet httpGet = new HttpGet(uri);
		CloseableHttpResponse response = null;
		try {
			// 执行请求
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				//请求体内容
				String content = EntityUtils.toString(response.getEntity(), "UTF-8");
				ShareResult shareResult = new ShareResult();
				shareResult.setCode(200);
				shareResult.setDetail(content);
				return shareResult;
			}
		} catch (Exception e) {
			log.error("发送POST请求出错 {}", uri, e);
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			//相当于关闭浏览器
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return  null;
	}

	/**
	 * 向指定 uri 发送 get 请求
	 * @param uri 指定的 uri
	 * @return 自己也可以改返回类型
	 */
	public static String getHeartbeat(String uri) {
		// 创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// 创建http GET请求
		HttpGet httpGet = new HttpGet(uri);
		CloseableHttpResponse response = null;
		String heartbeatResult;
		try {
			// 执行请求
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				//请求体内容
				heartbeatResult= EntityUtils.toString(response.getEntity(), "UTF-8");
				return heartbeatResult;
			}
			return null;
		} catch (Exception e) {
			log.error("发送POST请求出错 {}", uri, e);
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			//相当于关闭浏览器
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return  null;
	}
}


之前公司同事写了 Post 发送的数据为 formdata 类型的和 JSON 类型的,自己照葫芦画瓢写了单纯的 Post、Get。之前写的主要是 CRUD,这类东西可能写得不好,先简单做个记录吧,以后好回顾完善。

最后

以上就是内向云朵为你收集整理的HttpClient 发送 Http 请求工具类的全部内容,希望文章能够帮你解决HttpClient 发送 Http 请求工具类所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(36)

评论列表共有 0 条评论

立即
投稿
返回
顶部