HttpClientUtils工具类封装,doGet()、doPost()、doPut()、doDelete()

概述

HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本。

 

HttpClientUtils工具类封装,doGet()、doPost()、doPut()、doDelete()

1、doGet不带参数示例

		// 创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();

		// 创建http GET请求
		HttpGet httpGet = new HttpGet("https://xiaoyuan.zhaopin.com/api/sou?pageNumber=2");

		CloseableHttpResponse response = null;
		try
		{
			// 执行请求
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200)
			{
				String content = EntityUtils.toString(response.getEntity(), "UTF-8");
				System.out.println("内容长度:" + content.length());
				System.out.println(content);// 响应的内容
			}
		} finally
		{
			if (response != null)
			{
				response.close();
			}
			httpclient.close();
		}

 

2、doGet带参数示例

		// 创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();

		// 定义请求的参数
		URI uri = new URIBuilder("https://xiaoyuan.zhaopin.com/api/sou").setParameter("pageNumber", "1")
				.setParameter("keyWord", "java").build();

		System.out.println(uri);

		// 创建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");
				System.out.println(content);
			}
		} finally
		{
			if (response != null)
			{
				response.close();
			}
			httpclient.close();
		}

3、doPost不带参数示例

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        // 创建http POST请求
        HttpPost httpPost = new HttpPost("http://www.oschina.net/");

        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36");
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpPost);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(content);
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }

4、doPost带参数示例

		// 创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();

		// 添加信息
		HttpPost httpPost = new HttpPost("http://39.106.243.121/eto/add");

		// 设置2个post参数,一个是scope、一个是q
		List pairs = new ArrayList(0);
		pairs.add(new BasicNameValuePair("CityId", "530"));
		pairs.add(new BasicNameValuePair("CityName", "北京"));
		pairs.add(new BasicNameValuePair("SubCompanyNumber", "CC000773458D90000002000"));
		pairs.add(new BasicNameValuePair("CompanyName", "Oracle"));
		pairs.add(new BasicNameValuePair("CompanyTypeId", "5"));
		pairs.add(new BasicNameValuePair("IndustryName", "软件"));
		pairs.add(new BasicNameValuePair("CompanySize", "10000人以上"));
		pairs.add(new BasicNameValuePair("CompanyNumber", "DC000773458"));
		// 构造一个form表单式的实体
		UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(pairs);
		// 将请求实体设置到httpPost对象中
		httpPost.setEntity(formEntity);

		CloseableHttpResponse response = null;
		try
		{
			// 执行请求
			response = httpclient.execute(httpPost);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200)
			{
				String content = EntityUtils.toString(response.getEntity(), "UTF-8");
				System.out.println(content);
			}
		} finally
		{
			if (response != null)
			{
				response.close();
			}
			httpclient.close();
		}

 

5、HttpClientUtils工具类更精细化的封装

package com.huazai.b2c.aiyou.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
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.huazai.b2c.aiyou.repo.HttpResultData;

/**
 * 
 * @author HuaZai
 * @contact [email protected]
 *          
    * @description HttpClient工具类 *
* @className HttpUtil * @package com.huazai.b2c.aiyou.utils * @createdTime 2017年06月17日 * * @version V1.0.0 */ public class HttpClientUtils { private CloseableHttpClient httpClient; public HttpClientUtils() { httpClient = HttpClients.createDefault(); } /** * * @author HuaZai * @contact [email protected] * @title doGet *
    * @description 带参数的doGet请求 *
* @createdTime 2017年06月17日 * @param uri * @param map * @return * @throws Exception * @return HttpResultData * * @version : V1.0.0 */ public HttpResultData doGet(String uri, Map map) { CloseableHttpResponse response = null; try { // 1、创建URIBuilder对象 URIBuilder uriBuilder = new URIBuilder(uri); encapRequestParams(map, uriBuilder); // 3、创建 HttpGet对象 HttpGet httpGet = new HttpGet(uriBuilder.build()); // 4、使用httpClient发起请求 response = httpClient.execute(httpGet); // 5、解析返回结果,封装返回对象HttpResultData HttpResultData resultData = this.parseHttpResultData(response); // 打印日志输出 return resultData; } catch (Exception e) { e.printStackTrace(); // 打印日志输出 } finally { // 6、释放资源 try { if (response != null) { response.close(); } httpClient.close(); } catch (IOException e) { // 打印日志输出 e.printStackTrace(); } } return null; } /** * * @author HuaZai * @contact [email protected] * @title doGet *
    * @description 不带参数的doGet请求 *
* @createdTime 2017年06月17日 * @param uri * @return * @throws Exception * @return HttpResultData * * @version : V1.0.0 */ public HttpResultData doGet(String uri) throws Exception { return this.doGet(uri, null); } /** * * @author HuaZai * @contact [email protected] * @title doPost *
    * @description 带参数的doPost请求 *
* @createdTime 2017年06月17日 * @param uri * @param map * @return * @return HttpResultData * * @version : V1.0.0 * @throws Exception */ public HttpResultData doPost(String uri, Map map) { CloseableHttpResponse response = null; try { // 1、声明 HttpPost对象 HttpPost request = new HttpPost(); // 2、封装请求参数,请求数据表单 UrlEncodedFormEntity entity = this.encapRequestParams(map); // 3、设置请求数据表单 request.setEntity(entity); // 4、通过HttpClient执行请求 response = httpClient.execute(request); // 5、解析返回结果,封装返回对象HttpResultData HttpResultData resultData = this.parseHttpResultData(response); // 打印日志输出 return resultData; } catch (Exception e) { // 打印日志输出 e.printStackTrace(); } finally { // 6、释放资源 try { if (response != null) { response.close(); } httpClient.close(); } catch (IOException e) { // 打印日志输出 e.printStackTrace(); } } return null; } /** * * @author HuaZai * @contact [email protected] * @title doPost *
    * @description 不带参数的doPost请求 *
* @createdTime 2017年06月17日 * @param uri * @return * @return HttpResultData * * @version : V1.0.0 * @throws Exception */ public HttpResultData doPost(String uri) throws Exception { return this.doPost(uri, null); } /** * * @author HuaZai * @contact [email protected] * @title doPut *
    * @description 带参数的doPut请求 *
* @createdTime 2017年06月17日 * @param uri * @param map * @return * @return HttpResultData * * @version : V1.0.0 * @throws Exception */ public HttpResultData doPut(String uri, Map map) { CloseableHttpResponse response = null; try { // 1、生命HttpPut对象 HttpPut request = new HttpPut(); // 2、封装请求参数 UrlEncodedFormEntity entity = this.encapRequestParams(map); // 3、设置请求表单数据 request.setEntity(entity); // 4、通过HttpClient执行请求 response = httpClient.execute(request); // 5、封装解析返回结果,封装返回对象HttpResultData HttpResultData resultData = this.parseHttpResultData(response); // 打印日志输出 return resultData; } catch (Exception e) { // 打印日志输出 e.printStackTrace(); } finally { // 6、释放资源 try { if (response != null) { response.close(); } httpClient.close(); } catch (IOException e) { // 打印日志输出 e.printStackTrace(); } } return null; } /** * * @author HuaZai * @contact [email protected] * @title doPut *
    * @description 不带参数的doPut请求 *
* @createdTime 2017年06月17日 * @param uri * @return * @return HttpResultData * * @version : V1.0.0 * @throws Exception */ public HttpResultData doPut(String uri) throws Exception { return this.doPut(uri, null); } /** * * @author HuaZai * @contact [email protected] * @title doDelete *
    * @description 带参数的doDelete请求 *
* @createdTime 2017年06月17日 * @param uri * @param map * @return * @return HttpResultData * * @version : V1.0.0 * @throws Exception */ public HttpResultData doDelete(String uri, Map map) { CloseableHttpResponse response = null; try { // 1、创建URIBuilder对象 URIBuilder uriBuilder = new URIBuilder(uri); // 2、设置请求参数 this.encapRequestParams(map, uriBuilder); // 3、创建 HttpGet对象 HttpDelete request = new HttpDelete(uriBuilder.build()); // 4、使用httpClient发起请求 response = httpClient.execute(request); // 5、解析返回结果,封装返回对象HttpResultData HttpResultData resultData = this.parseHttpResultData(response); // 打印日志输出 return resultData; } catch (Exception e) { // 打印日志输出 e.printStackTrace(); } finally { // 6、释放资源 try { if (response != null) { response.close(); } httpClient.close(); } catch (IOException e) { // 打印日志输出 e.printStackTrace(); } } return null; } /** * * @author HuaZai * @contact [email protected] * @title doDelete *
    * @description 不带参数的doDelete请求 *
* @createdTime 2017年06月17日 * @param uri * @return * @return HttpResultData * * @version : V1.0.0 * @throws Exception */ public HttpResultData doDelete(String uri) throws Exception { return this.doDelete(uri, null); } /** * * @author HuaZai * @contact [email protected] * @title parseHttpResultData *
    * @description 解析返回结果,封装返回对象HttpResultData *
* @createdTime 2017年06月17日 * @param response * @return * @throws IOException * @return HttpResultData * * @version : V1.0.0 */ private HttpResultData parseHttpResultData(CloseableHttpResponse response) throws IOException { // 响应状态码 int code = response.getStatusLine().getStatusCode(); String body = null; // 响应消息体 HttpEntity httpEntity = response.getEntity(); if (httpEntity != null) { body = EntityUtils.toString(httpEntity, "UTF-8"); } // 封装返回实体 HttpResultData resultData = new HttpResultData(code, body); return resultData; } /** * * @author HuaZai * @contact [email protected] * @title encapRequestParams *
    * @description 封装请求参数,请求数据表单 *
* @createdTime 2017年06月17日 * @param map * @return * @throws Exception * @return UrlEncodedFormEntity * * @version : V1.0.0 */ private UrlEncodedFormEntity encapRequestParams(Map map) throws Exception { // 是否是带参数的请求 if (map != null) { // 声明表单容器 List parameters = new ArrayList<>(); for (Map.Entry entry : map.entrySet()) { // 封装容器 BasicNameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString()); parameters.add(nameValuePair); } // 创建表单实体 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "UTF-8"); return entity; } return null; } /** * * @author HuaZai * @contact [email protected] * @title encapRequestParams *
    * @description 设置请求参数 *
* @createdTime 2017年06月17日 * @param map * @param uriBuilder * @return void * * @version : V1.0.0 */ private void encapRequestParams(Map map, URIBuilder uriBuilder) { // 是否是带参数的请求 if (map != null) { for (Map.Entry entry : map.entrySet()) { // 封装请求参数 uriBuilder.addParameter(entry.getKey(), entry.getValue().toString()); } } } }

 

 

 


 好了,关于 HttpClientUtils工具类封装,doGet()、doPost()、doPut()、doDelete() 就写到这儿了,如果还有什么疑问或遇到什么问题欢迎扫码提问,也可以给我留言哦,我会一一详细的解答的。 
歇后语:“ 共同学习,共同进步 ”,也希望大家多多关注CSND的IT社区。


作       者: 华    仔
联系作者: [email protected]
来        源: CSDN (Chinese Software Developer Network)
原        文: https://blog.csdn.net/Hello_World_QWP/article/details/102912797
版权声明: 本文为博主原创文章,请在转载时务必注明博文出处!

你可能感兴趣的:(Utils)