HttpClient接口测试(详解加token传递实战)

邹坚壁
2023-12-01

HttpClient 接口测试

1.Get请求 操作步骤

​ get请求第一种情况接受参数,第二种情况传参

1.1无参数

		String url1="http://49.232.71.217:8899/common/skuList";
		
//		1、初始化HttpClient对象 
		CloseableHttpClient client=HttpClients.createDefault();
//		2、初始化HttpGet对象
		HttpGet get=new HttpGet(url3+para);
//		3、执行get请求,获得响应
		CloseableHttpResponse response=client.execute(get);
//		syso,打印出响应行
		System.out.println(response.getCode()+"  "+response.getReasonPhrase());
//		打印出响应头
		Header[] headers=response.getHeaders();
		for(Header header:headers) {
			System.out.println(header.getName()+":"+header.getValue());
		}
//		4、获得响应正文
		HttpEntity entity=response.getEntity();
//		5、获得响应内容
		String result=EntityUtils.toString(entity,"utf-8");
		System.out.println(result);
//		6、释放资源
		EntityUtils.consume(entity);
//		7、断开连接
		response.close();
		client.close();

2.Post请求

2.1有Form形式的参数

		String url = "http://49.232.71.217:8888/index.php/site/login";

		CloseableHttpClient client = HttpClients.createDefault();
		HttpPost post = new HttpPost(url);
//		3、设置Header属性Content-Type 		application/x-www-form-urlencoded
		post.setHeader("Content-Type", "application/x-www-form-urlencoded");
//		4、设置请求体LoginForm[username]=admin
		
//		HttpEntity user1 = new StringEntity("LoginForm[username]=admin&" + "LoginForm[password]=123456&"
//				+ "LoginForm[language]=zh_cn&" + "LoginForm[rememberMe]=0");
//		post.setEntity(user1);
//		或者采用下面的方式
		ArrayList<NameValuePair> user=new ArrayList<NameValuePair>();
		user.add(new BasicNameValuePair("LoginForm[username]", "admin"));
		user.add(new BasicNameValuePair("LoginForm[password]", "123456"));
		user.add(new BasicNameValuePair("LoginForm[language]", "zh_cn"));
		user.add(new BasicNameValuePair("LoginForm[rememberMe]", "0"));
		post.setEntity(new UrlEncodedFormEntity(user));

//		5、执行请求
		CloseableHttpResponse response = client.execute(post);

//		6、获得响应体
		HttpEntity response_entity = response.getEntity();

//		7、获得响应正文(字符串)
		String result = EntityUtils.toString(response_entity,"utf-8");
		System.out.println(result);

//		8、释放资源
		EntityUtils.consume(response_entity);

//		9、断开连接
		response.close();
		client.close();

2.2JSON形式的参数

		String url="http://49.232.71.217:8899/common/fgadmin/login";
		
		CloseableHttpClient client=HttpClients.createDefault();
		HttpPost post =new HttpPost(url);
//		3、设置Header属性
		post.setHeader("Content-Type", "application/json");
//		4、设置请求体
		HttpEntity user1=new StringEntity("{\"phoneArea\":\"86\"," + 
				"  \"phoneNumber\":\"2000\", " + 
				"  \"password\":\"netease123\" } ");
		
		StringEntity user2=new StringEntity("{\"phoneArea\":\"86\"," + 
				"  \"phoneNumber\":\"2000\", " + 
				"  \"password\":\"netease123\" } ");
		post.setEntity(user1);
		
//		5、执行请求
		CloseableHttpResponse response=client.execute(post);
		
//		6、获得响应体
		HttpEntity response_entity=response.getEntity();
		
//		7、获得响应正文(字符串)
		String result=EntityUtils.toString(response_entity);
		System.out.println(result);
		
//		8、释放资源
		EntityUtils.consume(response_entity);
		
//		9、断开连接
		response.close();
		client.close();

3.注意事项

​ 1.不能在一个接口中实例化多个client对象,多个对象不能连续操作,登录和查询无法衔接。

​ 2.如果URL地址中有中文注意转码问题。

​ 3.如果获取的数据是HTML类的注意用match正则表达式提取(这个例子主要是JSON)

4.排查思路

​ 1.把响应结果复制到记事本中,保存HTML,使用浏览器打开。

​ 2.代码使用代理,打开fidder抓包,查看请求体是否有中文乱码。

​ 3.fiddler 中再次执行该请求,如果没有问题,那就是header没有问题,请求体没有问题。

​ 4.请求编码问题。有可能servlet不能识别中文的参数,这时候出错考虑加编码方式。

post.setEntity(new UrlEncodedFormEntity(blog.Charset.forName("utf-8")));

5.HttpClient+Java+TestNG接口测试实战

​ 在这个接口测试中

1.post 登录 ,用户名和密码以JSON格式发送给服务器。

2. get 查询收货地址 , 记录下查出的地址,并且以字符串拼接的方式得到接下来查询费用的URL
3. get 请求 查询 上一步得到的地址的邮寄费用。
package Shop;

import static org.testng.AssertJUnit.assertEquals;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class Buyer {
	String loginUrl = "http://49.232.71.217:8899/common/fgadmin/login";
	
	String adressUrl = "http://49.232.71.217:8899/fgadmin/address/list";
	
	String feeUrl;
	String addressStr;
	CloseableHttpClient client;
	
	@BeforeClass
	public void initClient() {
		client= HttpClients.createDefault();
	}
	@AfterClass
	public void closeClient() throws IOException {
		client.close();
	}
	/*
	1、POST 登录
http://49.232.71.217:8899/common/fgadmin/login
{"phoneArea":"86",   
  "phoneNumber":"2000",     
  "password":"123456" } 
或者
{"phoneArea":"86",   
  "phoneNumber":"2001",     
  "password":"654321" } 

响应内容
{
    "code": "200",
    "message": "success"
}
失败
{
    "code": "400",
    "message": "用户名或者密码错误"
}
	*/
	@Test(priority = 1)
	public void submit() throws IOException, ParseException {
				
//		登录post		********************************
		
		
		

//		1.新建客户端		
		//this.client = HttpClients.createDefault();
//		2.实例化post请求对象
		HttpPost loginPost=new HttpPost(loginUrl);
//		3.设置Header属性
		loginPost.setHeader("Content-Type","application/json");
//		
		JSONObject user = new JSONObject();
//		{"phoneArea":"86",   
//			  "phoneNumber":"2000",     
//			  "password":"123456" } 
		user.put("phoneArea", "86");
		user.put("phoneNumber", "2000");
		user.put("password", "123456");
//		4.设置响应正文
		HttpEntity loginRequestBody = new StringEntity(user.toString());
		loginPost.setEntity(loginRequestBody);
		CloseableHttpResponse loginResponse = client.execute(loginPost);
		String loginResult = EntityUtils.toString(loginResponse.getEntity());
		
		System.out.println(loginResult);
		
		JSONObject jsonLoginResult = JSON.parseObject(loginResult);
		
		assertEquals(jsonLoginResult.getString("message"),"success");
		EntityUtils.consume(loginRequestBody);
		
		loginResponse.close();
				
		
		
		
		
//		查询运费get***************************************
		
		
	}
	
/*
3、GET 登录后 查询地址
http://49.232.71.217:8899/fgadmin/address/list
响应内容
{
    "code": 200,
    "message": "success",
    "list": [
        {
            "area": "滨江区",
            "addressDetail": "浙江大学",
            "province": "浙江省",
            "city": "杭州市",
            "receiverName": "张三",
            "id": "123456",
            "cellPhone": "12345678901"
        },
        {
            "area": "裕华区",
            "addressDetail": "河北师范大学",
            "province": "河北",
            "city": "石家庄市",
            "receiverName": "李四",
            "id": "111111",
            "cellPhone": "1234533301"
        }
    ]
}
*/
	@Test(priority = 2)
	public void adress() throws IOException, ParseException {
//		查询地址 get*************************************
		//CloseableHttpClient client = HttpClients.createDefault();
		
//		2.初始化HttpGet对象
		HttpGet adressGet = new HttpGet(adressUrl);
		
//		3.执行get请求,获取响应
		CloseableHttpResponse addressResponse = client.execute(adressGet);
		
//		4.获得响应正文
		HttpEntity addressEntity = addressResponse.getEntity();
		
//		5.获取响应内容
		String adressResult = EntityUtils.toString(addressEntity);
		System.out.println(adressResult);
		
		JSONObject result = JSONObject.parseObject(adressResult);
		JSONObject addressi = result.getJSONArray("list").getJSONObject(0);
		System.out.println(addressi.get("addressDetail"));
		
//		获取id 和地址方便getfee查询   id=1&addressDetail=浙江省_杭州市_滨江区
		String id = addressi.getString("id");
		String addressStr = addressi.getString("province")+"_"+addressi.getString("city")+"_"+addressi.getString("area");
	    String next_url = "http://49.232.71.217:8899/common/getTransportFee?id="+id+"&addressDetail="+URLEncoder.encode(addressStr,"utf-8");
	    this.addressStr =addressStr;
	    this.feeUrl = next_url;
	    System.out.println(next_url);
		
//		6.释放资源
		EntityUtils.consume(addressEntity);
		
//		7.断开连接
		addressResponse.close();	
		//client.close();
		
		
		
	}
	/*
	4、GET 登录后计算运费
地址从第三个接口返回结果组合而成 省_市_区
http://49.232.71.217:8899/common/getTransportFee?id=1&addressDetail=浙江省_杭州市_滨江区

响应内容
{
    "result": "6",
    "code": "200",
    "message": "success"
}
	*/
	@Test(priority = 3)
	public void getFee() throws IOException, ParseException {
	
//		2.初始化HttpGet对象
	         	3.执行get请求,获取响应
		CloseableHttpResponse response = client.execute(get);
		
//		4.获得响应正文
		HttpEntity entity = response.getEntity();
		
//		5.获取响应内容
		String result = EntityUtils.toString(entity);
		System.out.println(result);
		
		
		JSONObject jsonObject = JSONObject.parseObject(result);
		System.out.println("结果fee="+jsonObject.get("fee"));
//		6.释放资源
		EntityUtils.consume(entity);
		
//		7.断开连接
		response.close();	
		//client.close();
			
	
	}
	
	
	
	

}

6、Java正则表达式Pattern和Matcher

​ 三个常用的类:Pattern、Matcher、PatternSyntaxException。

​ 可以快速提取大量文本数据中的指定内容

​ java.util.regex是一个用正则表达式 对字符串进行匹配的类库包。

​ 首先一个Pattern实例制定了一个正则表达式经编译后的模式

​ 非常厉害的技术,极大的降低了文本处理难度

1.抓取文本内容(txt)

package com.gaoxin.regexp;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*
 * 体验正则表达式的威力
 * */

public class Regexp {
	public static void main(String[] args) {
		//假定编写了爬虫,从百度页面得到如下文本
		String content="1995年,互联网的蓬勃发展给了Oak机会。业界为了使死板、单调的静态网页能"
				+ "够“灵活”起来,急需一种软件技术来开发一种程序," +
                "这种程序可以通过网络传播并且能够跨平台运行。于是,世界各大IT企业为此纷纷投"
                + "入了大量的人力、物力和财力。这个时候," +
                "Sun公司想起了那个被搁置起来很久的Oak,并且重新审视了那个用软件编写的试验平台,"
                + "由于它是按照嵌入式系统硬件平台体系结构进行编写的,所以非常小," +
                "特别适用于网络上的传输系统,而Oak也是一种精简的语言,程序非常小,适合在网络上传输。"
                + "Sun公司首先推出了可以嵌入网页并且可以随同网页在网络上传输的Ap"
                + "plet(Applet是一种将小程序嵌入到网页中进行执行的技术),并将Oak更名为Java(在"
                + "申请注册商标时,发现Oak已经被人使用了,再想了一系列名字之后,最"
                + "终,使用了提议者在喝一杯Java咖啡时无意提到的Java词语)。5月23日,Sun公司在Sun"
                + " world会议上正式发布Java和HotJava浏览器。IBM、Apple、DEC、Ad"
                + "obe、HP、Oracle、Netscape和微软等各大公司都纷纷停止了自己的相关开发项目,竞"
                + "相购买了Java使用许可证,并为自己的产品开发了相应的Java平台。";

		/*//提取文章中的所有英文单词
		 * (1)传统方法使用遍历方式,代码量大,效率不高.
		 * (2)正则表达式`技术
		 * 
		 * */
		
//		1.先创建一个Pattern对象,模式对象,可以理解成一个正则表达式对象
//		小写的a到小写的z,大写的A到大写的Z;"+" 代表了可以有一到多.
		Pattern pattern = Pattern.compile("[a-zA-Z]+");
		
//		2.创建一个匹配器对象	
//		理解:就是matcher匹配器按照pattern(模式/样式),到content文本中去匹配
//		找到就返回true
		Matcher matcher=pattern.matcher(content);
		
//		3.可以开始循环匹配
		while(matcher.find()) {
//			匹配内容,文本放到m.group(0);
			System.out.println("找到:"+matcher.group(0));
				
		}
/*
		找到:Oak
		.
		.
		.
		找到:Java

 * */  
		
//		2.提取文章中所有的数字
		System.out.println("***********2.提取文章中所有的数字");
		Pattern pattern1 = Pattern.compile("[0-9]+");
		Matcher matcher1=pattern1.matcher(content);        
		while(matcher1.find()) {
//			匹配内容,文本放到m.group(0);
			System.out.println("找到:"+matcher1.group(0));
				
		}
		
//		3.提取数字和英文单词
		System.out.println("*********提取数字和英文单词");
		Pattern pattern2 = Pattern.compile("([0-9]+)|([a-zA-Z]+)");
		Matcher matcher2=pattern2.matcher(content);        
		while(matcher2.find()) {
//			匹配内容,文本放到m.group(0);
			System.out.println("找到:"+matcher2.group(0));
				
		}	
	
	}

}

2.抓取页面(html)

<input type="hidden" name="csrf_token" value="773a1ea35125aa44"/>
package com.gaoxin.regexp;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HtmlRegexp {
	public static void main(String[] args) {
		String content = "  <input type=\"hidden\" name=\"csrf_token\" value=\"773a1ea35125aa44\"/>";
//		1.先创建一个Pattern对象,模式对象,可以理解成一个正则表达式对象

		Pattern pattern = Pattern.compile("  <input type=\"hidden\" name=\"csrf_token\" value=\"(\\S*)\"/>");
		
//		2.创建一个匹配器对象	

		Matcher matcher=pattern.matcher(content);
		
//		3.可以开始循环匹配
		while(matcher.find()) {
//			匹配内容,文本放到m.group(0);
			System.out.println("找到:"+matcher.group(1));
				
		}
	}

}

HttpClient综合实战(token传递)

​ 涉及到了token获取。



package Collection;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class APITest {
	
//	API_URL
	String indexURL = "http://49.232.71.217:9999/";
	String loginUrl = "index.php?m=u&c=login&a=dorun";
	String token;
	String loginSuccess =indexURL+"index.php?m=u&c=login&a=welcome";
	String statu;
	String sendTxtUrl = indexURL+"index.php?c=post&a=doadd&_json=1&fid=5";
	String tid;
	String replyUrl = indexURL +"index.php?c=post&a=doreply&_getHtml=1";
	String quitUrl = indexURL+"index.php?m=u&c=login&a=logout";
	
//	初始化client
	CloseableHttpClient client;
	@BeforeClass
	public void initClient() {
		client= HttpClients.createDefault();
	}
	@AfterClass
	public void closeClient() throws IOException {
		client.close();
	}
	
//	1.访问主页get****************
	@Test(priority = 1)
	public void visitIndex() throws IOException, ParseException {
		System.out.println("1.访问主页get****************");
//		2.初始化HttpGet对象
		HttpGet get = new HttpGet(indexURL);
		
//		3.执行get请求,获取响应
		CloseableHttpResponse response = client.execute(get);
		
//		4.获得响应正文
		HttpEntity entity = response.getEntity();
		
//		5.获取响应内容
		String result = EntityUtils.toString(entity);
		//System.out.println(result);
//		用正则表达式匹配  <input type="hidden" name="csrf_token" value="773a1ea35125aa44"/>
		Pattern pattern = Pattern.compile("<input type=\"hidden\" name=\"csrf_token\" value=\"(\\S*)\"/>");
		
//		2.创建一个匹配器对象	

		Matcher matcher=pattern.matcher(result);
		
//		3.可以开始循环匹配
		while(matcher.find()) {
//			匹配内容,文本放到m.group(0);
			String token = matcher.group(1);
			this.token = token;
			System.out.println("statu="+token);
			break;
				
		}
		

		
//		6.释放资源
		EntityUtils.consume(entity);
		
//		7.断开连接
		response.close();			
	}
	

//	2、登录 post*****************
	@Test(priority = 2)
	public void login() throws IOException, ParseException {
		System.out.println("2、登录 post*****************");
		String url = indexURL+loginUrl;
//		2.实例化post请求对象
		HttpPost loginPost=new HttpPost(url);
//		3.设置Header属性
		loginPost.setHeader("Accept","application/json, text/javascript, */*; q=0.01");
		loginPost.setHeader("X-Requested-With","XMLHttpRequest");
		
		
//		
//		JSONObject user = new JSONObject();
//		username:gaoxin
//		password:123456 
//		backurl:http://localhost:8087/invite 
//		user.put("username", "sunnygx");
//		user.put("password", "123456");
//		user.put("backurl", "http://49.232.71.217:9999/");
//		user.put("invite", "");
//		user.put("csrf_token", this.token);
		ArrayList<NameValuePair> user = new ArrayList<>();
		
		user.add(new BasicNameValuePair("username", "sunnygao"));
		user.add(new BasicNameValuePair("password", "123456"));
		user.add(new BasicNameValuePair("backurl", "http://49.232.71.217:9999/"));
		user.add(new BasicNameValuePair("invite", ""));
		user.add(new BasicNameValuePair("csrf_token", this.token));
//		4.设置响应正文
		loginPost.setEntity(new UrlEncodedFormEntity(user));
//		5.执行请求
		CloseableHttpResponse loginResponse = client.execute(loginPost);

//		6、获得响应体
		HttpEntity response_entity = loginResponse.getEntity();
//		7.获得响应正文
		String loginResult = EntityUtils.toString(response_entity);
		
		System.out.println(loginResult);

		Pattern pattern = Pattern.compile("_statu%3D(\\S*)\",\"refresh\"");
		
//		2.创建一个匹配器对象	

		Matcher matcher=pattern.matcher(loginResult);
		
//		3.可以开始循环匹配
		while(matcher.find()) {
//			匹配内容,文本放到m.group(0);
			String statu = matcher.group(1);
			this.statu = statu;
			System.out.println("statu="+statu);
			break;
				
		}
		
	
		EntityUtils.consume(response_entity);
		
		loginResponse.close();		
	} 
	
//	3、登录成功GET******************** get的参数在url中。
//	值是从【登录接口】的返回值referer字段中_statu%3D
	@Test(priority = 3)
	public void loginSucess() throws IOException, ParseException {
		System.out.println("3、登录成功GET******************** ");
		HashMap<String,String> para = new HashMap<String,String>();
		para.put("_statu", this.statu);
		System.out.println(loginSuccess+"&"+mapToString(para));
//		2.初始化HttpGet对象
		HttpGet get = new HttpGet(loginSuccess+"&"+mapToString(para));
		
//		3.执行get请求,获取响应
		CloseableHttpResponse response = client.execute(get);
		
//		4.获得响应正文
		HttpEntity entity = response.getEntity();
		
//		5.获取响应内容
		String result = EntityUtils.toString(entity);
		//System.out.println(result);
		
	}
	public static String mapToString(HashMap<String, String> para) {
		
		StringBuilder builder = new StringBuilder();
		//builder.append("?");
		int size = para.size();
//		遍历map
		for(Map.Entry<String, String> entry:para.entrySet()) {
			String key = entry.getKey();
			String value = entry.getValue();
			
			builder.append(key+"="+value);
			size--;
			if(size>=1) {
				builder.append("&");
			}
			
		}
		return builder.toString();
		
	}	

/*
name="atc_title"  3
name="atc_content"  333
name="pid"
name="tid"
name="special"  default
name="reply_notice"	1
name="csrf_token"   c996ab10b92c64f1*/

//	*****************4.发帖	POST form
	@Test(priority = 4)
	public void test4SendText() throws IOException, ParseException {
		System.out.println("*****************4.发帖");
		String url = sendTxtUrl;
//		2.实例化post请求对象
		HttpPost post=new HttpPost(url);
//		3.设置Header属性


		ArrayList<NameValuePair> booke = new ArrayList<>();
//		给标题加时间。
		Date now = new Date( );
		SimpleDateFormat ft = new SimpleDateFormat ("MM.dd'at'hh:mm:ss");
		String title = ""+ft.format(now);
	    String text = "I love testing"+ft.format(now);
	    System.out.println(text);
		

	    booke.add(new BasicNameValuePair("atc_title", title));
	    booke.add(new BasicNameValuePair("atc_content", text));
	    booke.add(new BasicNameValuePair("pid", ""));
	    booke.add(new BasicNameValuePair("tid", ""));
	    booke.add(new BasicNameValuePair("special", "default"));
	    booke.add(new BasicNameValuePair("reply_notice", "1"));
	    booke.add(new BasicNameValuePair("csrf_token", this.token));
//		4.设置响应正文
		post.setEntity(new UrlEncodedFormEntity(booke));
//		5.执行请求
		CloseableHttpResponse response = client.execute(post);

//		6、获得响应体
		HttpEntity response_entity = response.getEntity();
//		7.获得响应正文
		String result = EntityUtils.toString(response_entity);
		
		System.out.println(result);
		
//		8.获取tid  php%3Ftid%3D602%26fid%3D5","refresh":true,"  Pattern.compile("_statu%3D(\\S*)\",\"refresh\"");
		
		Pattern pattern = Pattern.compile("tid%3D(\\S*)\",\"refresh\"");
		
//		2.创建一个匹配器对象	

		Matcher matcher=pattern.matcher(result);
		
//		3.可以开始循环匹配
		while(matcher.find()) {
//			匹配内容,文本放到m.group(0);
			String tid = matcher.group(1);
			this.tid = tid;
			System.out.println("tid="+tid);
			break;
				
		}	
		System.out.println("tid = "+tid);
		EntityUtils.consume(response_entity);
		
		response.close();			
		
	}
//	****************5、回帖 post
	@Test(priority = 5)
	public void test5Reply() throws IOException, ParseException, InterruptedException {
		
		System.out.println("****************5、回帖 post");
		Thread.sleep(5000);
		String url = replyUrl;
//		2.实例化post请求对象
		HttpPost post=new HttpPost(url);
//		3.设置Header属性


		ArrayList<NameValuePair> booke = new ArrayList<>();
//		给标题加时间。
		Date now = new Date( );
		SimpleDateFormat ft = new SimpleDateFormat ("MM.dd'at'hh:mm:ss");

	    String text = "I love testing too"+ft.format(now);
	    System.out.println(text);
		


	    booke.add(new BasicNameValuePair("atc_content", text));
	
	    booke.add(new BasicNameValuePair("tid", this.tid));

	    booke.add(new BasicNameValuePair("csrf_token", this.token));
//		4.设置响应正文
		post.setEntity(new UrlEncodedFormEntity(booke));
//		5.执行请求
		CloseableHttpResponse response = client.execute(post);

//		6、获得响应体
		HttpEntity response_entity = response.getEntity();
//		7.获得响应正文
		String result = EntityUtils.toString(response_entity);
		
		//System.out.println(result);
		
	
		EntityUtils.consume(response_entity);
		
		response.close();					
	}
	
//	6.退出****************
	@Test(priority = 6)
	public void test6Quit() throws IOException, ParseException {
		System.out.println("6.退出****************");
//		2.初始化HttpGet对象
		HttpGet get = new HttpGet(quitUrl);
		
//		3.执行get请求,获取响应
		CloseableHttpResponse response = client.execute(get);
		
//		4.获得响应正文
		HttpEntity entity = response.getEntity();
		
//		5.获取响应内容
		String result = EntityUtils.toString(entity);
		System.out.println(result);

		
//		6.释放资源
		EntityUtils.consume(entity);
		
//		7.断开连接
		response.close();				
	}
	

}

eHttpResponse response = client.execute(post);

// 6、获得响应体
HttpEntity response_entity = response.getEntity();
// 7.获得响应正文
String result = EntityUtils.toString(response_entity);

	//System.out.println(result);
	

	EntityUtils.consume(response_entity);
	
	response.close();					
}

// 6.退出****************
@Test(priority = 6)
public void test6Quit() throws IOException, ParseException {
System.out.println(“6.退出****************”);
// 2.初始化HttpGet对象
HttpGet get = new HttpGet(quitUrl);

// 3.执行get请求,获取响应
CloseableHttpResponse response = client.execute(get);

// 4.获得响应正文
HttpEntity entity = response.getEntity();

// 5.获取响应内容
String result = EntityUtils.toString(entity);
System.out.println(result);

// 6.释放资源
EntityUtils.consume(entity);

// 7.断开连接
response.close();
}

}


 类似资料: