Java-处理POST-MAN请求HttpClient的使用(Get请求中的Cookie、Header、与参数的处理)

1、HttpClient模拟一个get请求的Demo

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.3</version>
</dependency>
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.2.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-core</artifactId>
    <version>1.2.0</version>
</dependency>

2、测试一:代码实现 模拟baidu的Get请求 

package cn.Demo.HttpClient;

import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.testng.annotations.Test;
/**
 * HttpClient get请求模拟请求baidu获取返回值
 * */
public class GetDemo {
	@Test
	public void baiduReturn() throws Exception, IOException{
		//创建Get对象 请求URL要写全 否则会报Host的异常
		HttpGet get = new HttpGet("http://www.baidu.com");
		//创建get方法的执行对象
		//HttpClient client = new DefaultHttpClient();
        	// 创建get方法的执行对象 HttpClient4.X之后是这样创建client对象的
		CloseableHttpClient client = HttpClients.createDefault();
		//获取response对象
		HttpResponse response = client.execute(get);
		//将response对象转换成String类型
		String responseStr = EntityUtils.toString(response.getEntity(),"utf-8");
		System.out.println(responseStr);
	}
}

查看打印 可以看到response的html返回页全部都打印出来了 :

 3、测试二:获取Cookies信息

3.1、编写Test.json文件(POST_MAN导出的JSON文件)

实际这是两个接口 /GetDemo/withCookies接口是获取Cookies,/GetDemo/useCookies接口是使用cookies才能访问

[
	{		
		"description":"Mock模拟接口,返回Cookies",
		"request":{			
			"uri":"/GetDemo/withCookies",
			"method":"get"
		},		
		"response":{
			"json":{
				"Code":"Success",
				"Data":{
					"Link":"./locatin/xxx.jpg",
					"Message":"Mock模拟的带Header信息的请求"
				}
			},
			"cookies":{
				"sessionID":"AABBCCDD"
				}
		}	
	},	
	{	
		"description":"Mock模拟接口,使用sessionID才能访问成功",
		"request":{
			"uri":"/GetDemo/useCookies",
			"method":"get",
			"cookies":{
				"sessionID":"AABBCCDD"
				}
			},
			
		"response":{
			"json":{
				"Link":"/GetDemo/useCookies",
				"Data":{
					"name":"Anndy",
					"age":18,
					"Time":"2018-9-9"
				}
			}
		}
	}
]

3.2、HttpClient4.x获取Cookie

 

public static void main(String[] args) {
	try {
		// 创建Get对象 请求URL要写全 否则会报Host的异常
		HttpGet get = new HttpGet("http://localhost:8888/GetDemo/withCookies");
		//创建CookieStore对象用来获取cookie
		CookieStore cookieStore = new BasicCookieStore();			
		// 创建get方法的执行对象 HttpClient4.X之后是这样创建client对象的
		CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
		// 获取response对象
		HttpResponse response= client.execute(get);
		// 将response对象转换成String类型
		String responseStr = EntityUtils.toString(response.getEntity(), "utf-8");
		System.out.println(responseStr);
		//获取到的Cookie是应该Cookie为泛型的List集合
		List<Cookie> cookies = cookieStore.getCookies();
		for (Cookie cookie : cookies) {
			System.out.println(cookie.toString());
			System.out.println(cookie.getName()+"--"+cookie.getValue());
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
}

执行结果 :

4、测试三:HttpClient4.x设置访问是添加设置Cookies信息 

同样还是2.1的Mock文件,携带Cookie访问的代码如下:

public static void main(String[] args) {
	try {
		// 创建get访问对象
		HttpGet get = new HttpGet("http://localhost:8889/GetDemo/useCookies");
		// 创建CookieStore对象用来管理cookie
		CookieStore cookieStore = new BasicCookieStore();
		//new BasicClientCookie对象 用来注入cookie
		BasicClientCookie cookie = new BasicClientCookie("sessionID", "AABBCCDD");
		
		cookie.setDomain("localhost");//设置cookie的作用域
		
		cookieStore.addCookie(cookie);//将cookie添加到cookieStore中
		// 创建get方法的执行对象 HttpClient4.X之后是这样创建client对象 设置cookies和header信息
		CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
		HttpResponse response = client.execute(get);
		// 将response对象转换成String类型
		String responseStr = EntityUtils.toString(response.getEntity(), "utf-8");
		System.out.println(responseStr);
		
	} catch (Exception e) {
		e.printStackTrace();
	}
}

5、测试四:Get请求中设置Header信息 

JSON文件请求格式文件如下:

[
	{		
		"description":"这是Mock接口,带Header和参数的Demo",
		"request":{			
			"uri":"/GetDemo/withHeaders",
			"method":"get",
			"headers":{
				"context-Type":"AA",
				"Angent":"BB"
			},
			"queries":{
				"name":"Anndy",
				"age":"18"
			}
		},		
		"response":{
			"json":{
				"Code":"Success",
				"Data":{
					"Link":"./locatin/xxx.jpg",
					"Message":"Mock模拟的带Header信息的请求"
				}			
			}
		}			
	}
]

JAVA代码实现如下:

public static void main(String[] args) {
	try {
		//创建URLBuilder对象
		URIBuilder uriBuilder = new URIBuilder("http://localhost:8889/GetDemo/withHeaders");
		//创建集合 添加参数
		List<NameValuePair> list = new LinkedList<>();
		BasicNameValuePair param1 = new BasicNameValuePair("name", "Anndy");
		BasicNameValuePair param2 = new BasicNameValuePair("age", "18");
		list.add(param1);
		list.add(param2);
		uriBuilder.addParameters(list);
		// 创建get访问对象
		HttpGet get = new HttpGet(uriBuilder.build());
		//设置Headers头信息
		get.setHeader("context-Type", "AA");
		get.setHeader("Angent", "BB");
		CloseableHttpClient client = HttpClients.createDefault();
		HttpResponse response = client.execute(get);
		// 将response对象转换成String类型
		String responseStr = EntityUtils.toString(response.getEntity(), "utf-8");
		System.out.println(responseStr);
	} catch (Exception e) {
		e.printStackTrace();
	}
}

6、测试五:POS请求中设置Header,和BODY参数信息  

JSON文件格式:

{
	"info": {
		"_postman_id": "6d1a9d03-ccc2-41b8-bed0-7cab9d1d829c",
		"name": "test",
		"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
	},
	"item": [
		{
			"name": "测试接口而已",
			"request": {
				"method": "POST",
				"header": [
					{
						"key": "Content-Type",
						"name": "Content-Type",
						"type": "text",
						"value": "application/x-www-form-urlencoded",
						"disabled": true
					},
					{
						"key": "apikey",
						"type": "text",
						"value": "XXXXXXXXXXXXXXXXXXXXX"
					}
				],
				"body": {
					"mode": "urlencoded",
					"urlencoded": [
						{
							"key": "test1",
							"value": "zhangyu373",
							"type": "text"
						},
						{
							"key": "test2",
							"value": "1",
							"type": "text"
						},
						{
							"key": "test3",
							"value": "100",
							"type": "text"
						},
						{
							"key": "test4",
							"value": "2019-12-01",
							"type": "text"
						}
					]
				},
				"url": {
					"raw": "http://xxxxxxxxxx.xxx.com.cn/env-101/por-5903/newdbtest/sign/xxxxx",
					"protocol": "http",
					"host": [
						"opentest-api",
						"test",
						"test",
						"cn"
					],
					"path": [
						"env-101",
						"por-5903",
						"newdbtest",
						"sign",
						"gateway",
						"SecondProject",
						"rest",
						"bgy",
						"getDeptSignInfo"
					]
				}
			},
			"response": []
		}
	],
	"protocolProfileBehavior": {}
}

代码实现:

    public static void main(String[] args) {
        try {
            //创建URLBuilder对象
            URIBuilder uriBuilder = new URIBuilder("http://xxxxxxxxxx.xxx.com.cn/env-101/por-5903/newdbtest/sign/xxxxx");
            //创建集合Body添加参数
            List<NameValuePair> list = new LinkedList<>();
            BasicNameValuePair param1 = new BasicNameValuePair("test1", "test11");
            BasicNameValuePair param2 = new BasicNameValuePair("test2", "1");
            BasicNameValuePair param3 = new BasicNameValuePair("test3", "100");
            BasicNameValuePair param4 = new BasicNameValuePair("test4", "2019-12-05");
            list.add(param1);
            list.add(param2);
            list.add(param3);
            list.add(param4);
            uriBuilder.addParameters(list);
            HttpPost post = new HttpPost(uriBuilder.build());
            //设置Headers头信息
            post.addHeader("Content-Type", "application/x-www-form-urlencoded");
            post.addHeader("apikey", "xxxxxxxxxxxxx");
            
            CloseableHttpClient client = HttpClients.createDefault();
            HttpResponse response = client.execute(post);
            // 将response对象转换成String类型
            String responseStr = EntityUtils.toString(response.getEntity(), "utf-8");
            System.out.println(responseStr);
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

猜你喜欢

转载自blog.csdn.net/bj_chengrong/article/details/103403597