使用org.apache.httpcomponents.httpclient进行Post和get请求测试

再写博客之前,先感谢两位大佬的博客,他们的博客是整体思路,我的代码只是我个人的测试总结

第一位,开源中国的  若杰,博客连接地址:地址

第二位,csdn的  William_Wei007 博客连接地址:地址

总结两位大佬的博客,做个人测试使用,还望大佬海涵。话不多说,接入正题。

公司最近进行项目的研发,需要项目后台接入运营商IOT平台,但涉及到后台和后台之间的通信,哎,作为小白一脸懵逼,但我有一颗好奇的心,想研究完玩。

大家都晓得,服务器之间的通信采用http协议实现,所以有客户端和服务器端的说法(这句话我预感有问题,懂行的大佬给个面子,下方留言指出),HttpClient是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

一、库文件的导入

我采用的Maven开发,为啥使用Maven(纯粹的感觉是看源码容易),对于项目需要进行HttpClient通信,需要再pom种增加一些库文件

<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.3</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.4</version>
		</dependency>

上面第一个HttpClient是通信库文件,下面的commons-lang3是我们需要用到的工具包文件。

二、按照  若杰  大佬统计的步骤

1、创建CloseableHttpClient对象。
2、创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
3、如果需要发送请求参数,可可调用setEntity(HttpEntity entity)方法来设置请求参数。setParams方法已过时(4.4.1版本)。
4、调用HttpGet、HttpPost对象的setHeader(String name, String value)方法设置header信息,或者调用setHeaders(Header[] headers)设置一组header信息。
5、调用CloseableHttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个CloseableHttpResponse。
6、调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容;调用CloseableHttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头。
7、释放连接。无论执行方法是否成功,都必须释放连接

实现基本操作

三、创建代码框架

我个人创建的就是简单的ssm框架格式,测试采取ajax请求后台,触发信息通信。

四、后台相关代码

页面部分(只打印核心代码)

<button id="btnTestPost" type="button">通信测试post</button><br/>
<button id="btnTestGet" type="button">通信测试get</button><br/>

$("#btnTestPost").click(function(){
			$.ajax({
				url:"nginxTest",
				data: {
					"name": "香蕉",
					"1":"apple"
				},
				dataType: 'json',
				type: 'post',
				timeout: 10000,
				traditional:true,//阻止深度序列化参数对象
				headers: {
					'ContentType': 'application/json',
					"headerVal":"6666666777"
				},
				success: function(res) {
					console.log(JSON.stringify(res));

				},
				error: function(xhr, type, errorThrown) {
					
				}
			});
		});
		
		$("#btnTestGet").click(function(){
			$.ajax({
				url:"nginxGet",
				data: {
					"name": "香蕉",
					"1":"apple"
				},
				dataType: 'json',
				type: 'get',
				timeout: 10000,
				traditional:true,//阻止深度序列化参数对象
				headers: {
					'ContentType': 'application/json',
					"headerVal":"6666666777"
				},
				success: function(res) {
					console.log(JSON.stringify(res));

				},
				error: function(xhr, type, errorThrown) {
					
				}
			});
		});

后台逻辑部分

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.ParseException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.linkpower.http.HttpClientUtils;
import net.sf.json.JSONObject;

@Controller
public class ControllerTest {
	private static Logger log = Logger.getLogger(Controller.class);

	// 测试公司服务器nginx
	@RequestMapping(value = "/nginxTest", method = RequestMethod.POST)
	@ResponseBody // 将返回的 map数据类型转化为json进行返回前台
	public Object nginxTest(HttpServletRequest request, HttpServletResponse response) {
		log.info("-------------->/nginxTest");
		String url = "http://localhost:80/ssm/nginxTest2";
		Map<String,String> paramMap = new HashMap<String,String>();
		paramMap.put("name", request.getParameter("name"));
		try {
			String getResult = HttpClientUtils.simplePost(url, paramMap, null);
			log.info("getResult--------->"+getResult);
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		String names = (String) request.getParameter("name");
		log.info("获取前台传递数据    names------>" + names);
		JSONObject json = new JSONObject();
		json.put("code", 200);
		json.put("msg", "ok");
		json.put("data", names + "xiangjiao");
		return json;
	}
	
	@RequestMapping(value = "/nginxTest2", method = RequestMethod.POST)
	@ResponseBody // 将返回的 map数据类型转化为json进行返回前台
	public Object nginxTest2(HttpServletRequest request, HttpServletResponse response) {
		log.info("-------------->/nginxTest2");
		String names = (String) request.getParameter("name");
		log.info("获取前台传递数据    names------>" + names);
		return "666666";
	}
	
	// 测试公司服务器nginx
		@RequestMapping(value = "/nginxGet", method = RequestMethod.GET)
		@ResponseBody // 将返回的 map数据类型转化为json进行返回前台
		public Object nginxGet(HttpServletRequest request, HttpServletResponse response) {
			log.info("-------------->/nginxGet");
			String url = "http://localhost:80/ssm/nginxTestGet";
			Map<String,String> paramMap = new HashMap<String,String>();
			paramMap.put("name", request.getParameter("name"));
			paramMap.put("msg", "香蕉不拿拿先生");
			try {
				String getResult = HttpClientUtils.simpleGet(url, paramMap, null);
				log.info("getResult--------->"+getResult);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			String names = (String) request.getParameter("name");
			log.info("获取前台传递数据    names------>" + names);
			JSONObject json = new JSONObject();
			json.put("code", 200);
			json.put("msg", "ok");
			json.put("data", names + "xiangjiao");
			return json;
		}
		
		@RequestMapping(value = "/nginxTestGet", method = RequestMethod.GET)
		@ResponseBody // 将返回的 map数据类型转化为json进行返回前台
		public Object nginxTestGet(HttpServletRequest request, HttpServletResponse response) {
			log.info("-------------->/nginxTestGet");
			String names = (String) request.getParameter("name");
			log.info("获取前台传递数据    names------>" + names);
			return "777777";
		}
}

工具类文件

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.StatusLine;
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.client.utils.URLEncodedUtils;
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 java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 封装http请求
 * @author 76519
 *
 */
public class HttpClientUtils {

    private static Log log = LogFactory.getLog(HttpClientUtils.class);

    private final static String DEFAULT_ENCODING = "UTF-8";
    private final static int DEFAULT_CONNECT_TIMEOUT = 5000; // 设置连接超时时间,单位毫秒
    private final static int DEFAULT_CONNECTION_REQUEST_TIMEOUT = 1000;// 设置从connect Manager获取Connection 超时时间,单位毫秒
    private final static int DEFAULT_SOCKET_TIMEOUT = 5000;// 请求获取数据的超时时间,单位毫秒 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用

    /**
     * 简单http post请求
     * @param url 地址
     * @param paramMap  参数
     * @param encoding  编码
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public static String simplePost(String url, Map<String,String> paramMap, String encoding) throws ParseException, IOException {
        String body = "";
        encoding = StringUtils.isBlank(encoding)?DEFAULT_ENCODING:encoding;
        //1、创建CloseableHttpClient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //2、创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
        HttpPost httpPost = postForm(paramMap,url,DEFAULT_ENCODING);
        //执行请求操作,并拿到结果(同步阻塞)
        CloseableHttpResponse response = null;
        try {
        	//5、调用CloseableHttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个CloseableHttpResponse。
            response = client.execute(httpPost);
            //6、调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容;调用CloseableHttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头。
            StatusLine status = response.getStatusLine();
            log.info("请求回调状态               :"+status);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, encoding);
                log.info("请求回调数据               :"+body);
            }
            //7、释放连接。无论执行方法是否成功,都必须释放连接
            EntityUtils.consume(entity);
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
            log.error("简单post请求遇到UnSpEcode异常",e);
            throw new IOException(e);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("简单post请求遇到IO异常",e);
            throw new IOException(e);
        } catch (ParseException e) {
            e.printStackTrace();
            log.error("简单post请求遇到PE异常",e);
            throw new ParseException();
        } finally{
            //释放链接
            response.close();
        }
        return body;
    }

   /**
    * post请求url与请求参数组装
    * @param paramMap
    * @param url
    * @param encoding
    * @return
    * @throws UnsupportedEncodingException
    */
    private static HttpPost postForm(Map<String,String> paramMap,String url,String encoding) throws UnsupportedEncodingException {
        HttpPost httpPost = new HttpPost(url);
        //装填参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        if(paramMap!=null){
            for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        //3、如果需要发送请求参数,可可调用setEntity(HttpEntity entity)方法来设置请求参数。setParams方法已过时(4.4.1版本)
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));
        //4、调用HttpGet、HttpPost对象的setHeader(String name, String value)方法设置header信息,或者调用setHeaders(Header[] headers)设置一组header信息。
        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(DEFAULT_CONNECT_TIMEOUT).setConnectionRequestTimeout(DEFAULT_CONNECTION_REQUEST_TIMEOUT)
                .setSocketTimeout(DEFAULT_SOCKET_TIMEOUT).build();
        httpPost.setConfig(requestConfig);
        return httpPost;
    }
    /**
     * 简单get请求传输
     * @param url
     * @param paramMap
     * @param encoding
     * @return
     */
    public static String simpleGet(String url, Map<String,String> paramMap, String encoding){
    	String body = "";
        encoding = StringUtils.isBlank(encoding)?DEFAULT_ENCODING:encoding;
        //1、创建CloseableHttpClient对象
        CloseableHttpClient client = HttpClients.createDefault();
        
        //2、创建get请求
        HttpGet httpGet = new HttpGet(url);
      //装填参数
        List<NameValuePair> lists = new ArrayList<NameValuePair>();
        if(paramMap != null){
        	//每个key-value构成一个entrySet对象
            Set<Map.Entry<String, String>> setMap = paramMap.entrySet();
            //遍历对象  将值保存list集合种
            for (Map.Entry<String, String> entry:setMap) {
    			lists.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
    		}
        }
        //将传递参数  编码化
        String param = URLEncodedUtils.format(lists, encoding);
        log.info("simpleGet------->"+param);
        //设置数据
        httpGet.setURI(URI.create(url+"?"+param));
        log.info("simpleGet --- url------->"+httpGet.getURI().toString());
        //配置连接参数信息
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(DEFAULT_CONNECT_TIMEOUT).setConnectionRequestTimeout(DEFAULT_CONNECTION_REQUEST_TIMEOUT)
                .setSocketTimeout(DEFAULT_SOCKET_TIMEOUT).build();
        httpGet.setConfig(requestConfig);
        
      //执行请求操作,并拿到结果(同步阻塞)
        CloseableHttpResponse response = null;
        try {
        	//5、调用CloseableHttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个CloseableHttpResponse。
            response = client.execute(httpGet);
            //6、调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容;调用CloseableHttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头。
            StatusLine status = response.getStatusLine();
            log.info("get请求回调状态               :"+status);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, encoding);
                log.info("get请求回调数据               :"+body);
            }
            //7、释放连接。无论执行方法是否成功,都必须释放连接
            EntityUtils.consume(entity);
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
            log.error("简单get请求遇到UnSpEcode异常",e);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("简单get请求遇到IO异常",e);
        } catch (ParseException e) {
            e.printStackTrace();
            log.error("简单get请求遇到PE异常",e);
            throw new ParseException();
        } finally{
            //释放链接
            try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
        return body;
    }
}

五、测试结果打印

post通信

2019-03-11 22:00:21 -1908329 [http-nio-80-exec-3] INFO    - -------------->/nginxTest
2019-03-11 22:00:21 -1908351 [http-nio-80-exec-5] INFO    - -------------->/nginxTest2
2019-03-11 22:00:21 -1908352 [http-nio-80-exec-5] INFO    - 获取前台传递数据    names------>香蕉
2019-03-11 22:00:21 -1908353 [http-nio-80-exec-3] INFO    - 请求回调状态               :HTTP/1.1 200 OK
2019-03-11 22:00:21 -1908354 [http-nio-80-exec-3] INFO    - 请求回调数据               :666666
2019-03-11 22:00:21 -1908354 [http-nio-80-exec-3] INFO    - getResult--------->666666
2019-03-11 22:00:21 -1908354 [http-nio-80-exec-3] INFO    - 获取前台传递数据    names------>香蕉

get通信

2019-03-11 22:00:54 -1941498 [http-nio-80-exec-4] INFO    - -------------->/nginxGet
2019-03-11 22:00:54 -1941503 [http-nio-80-exec-4] INFO    - simpleGet------->msg=%E9%A6%99%E8%95%89%E4%B8%8D%E6%8B%BF%E6%8B%BF%E5%85%88%E7%94%9F&name=%E9%A6%99%E8%95%89
2019-03-11 22:00:54 -1941504 [http-nio-80-exec-4] INFO    - simpleGet --- url------->http://localhost:80/ssm/nginxTestGet?msg=%E9%A6%99%E8%95%89%E4%B8%8D%E6%8B%BF%E6%8B%BF%E5%85%88%E7%94%9F&name=%E9%A6%99%E8%95%89
2019-03-11 22:00:54 -1941519 [http-nio-80-exec-9] INFO    - -------------->/nginxTestGet
2019-03-11 22:00:54 -1941519 [http-nio-80-exec-9] INFO    - 获取前台传递数据    names------>香蕉
2019-03-11 22:00:54 -1941521 [http-nio-80-exec-4] INFO    - get请求回调状态               :HTTP/1.1 200 OK
2019-03-11 22:00:54 -1941521 [http-nio-80-exec-4] INFO    - get请求回调数据               :777777
2019-03-11 22:00:54 -1941521 [http-nio-80-exec-4] INFO    - getResult--------->777777
2019-03-11 22:00:54 -1941521 [http-nio-80-exec-4] INFO    - 获取前台传递数据    names------>香蕉

猜你喜欢

转载自blog.csdn.net/qq_38322527/article/details/88410673