【支持远程调试】post方法请求回来的文字乱码导致接口执行失败

来源:9-6 Post方法的访问实战

蚂蚁也是肉

2020-01-17

从json文件中获取的post请求乱码

1、post方法

/**
	 * 使用httpclient进行http通信
	 * 
	 * Post请求
	 */
	@Test
	public void httpclientPost() throws Exception {
		// String postUrl = "http://localhost:8081/postDemo";
		String postUrl = "http://139.9.152.127:8081/postParam";
		// List<NameValuePair> parameters=null;
		List<NameValuePair> parameters = new ArrayList<NameValuePair>();
		System.out.println(postUrl);

		// 创建HttpClient对象
		HttpClient client = HttpClients.createDefault();

		// 创建POST请求
		HttpPost post = new HttpPost(postUrl);

		// 创建一个List容器,用于存放基本键值对(基本键值对即:参数名-参数值)--> parameters
		/**
		 * "name":"xiaohua", "sex":"women"
		 */
		BasicNameValuePair basicName = new BasicNameValuePair("name", "xiaohua");
		BasicNameValuePair basicSex = new BasicNameValuePair("sex", "women");
		parameters.add(basicName);
		parameters.add(basicSex);
		// 向POST请求中添加消息实体
		post.setEntity(new UrlEncodedFormEntity(parameters, "utf-8"));

		// 得到响应并转化成字符串
		HttpResponse response = client.execute(post);
		HttpEntity httpEntity = response.getEntity();
		String result = EntityUtils.toString(httpEntity, "utf-8");
		System.out.println(result);
		String expected="胡汉三带着小花Post参数回来了!";
		Assert.assertEquals(result, expected);
	}

2、json文件

[
{
"description":"这是我们第一个mock例子",
"request":{
"uri":"/demo"
},
"response":{
"text":"第一个MOCO框架demo"
}
},

{
"description":"这是一个没有参数的get请求",
"request":{
"uri":"/getDemo",
"method":"get"
},
"response":{
"text":"我胡汉三又回来了"
}
},

{
"description":"这是一个带参数的get请求",
"request":{
"uri":"/getParam",
"method":"get",
"queries":{
"name":"huhansan",
"age":"29"
}
},
"response":{
"text":"我胡汉三又回来了"
}
},

{
"description":"这是一个带参数的get请求",
"request":{
"uri":"/getParam",
"method":"get",
"queries":{
"name":"xiaohua",
"age":"20"
}
},
"response":{
"text":"我小花三又回来了"
}
},

{
"description":"模拟一个不带参数的Post请求",
"request":{
"uri":"/postDemo",
"method":"post"
},
"response":{
"text":"这是一个不带参数的post请求!"
}
},
{
"description":"模拟一个带参数的Post请求",
"request":{
"uri":"/postParam",
"method":"post",
"forms":{
"name":"xiaohua",
"sex":"women"
}
},
"response":{
"text":"胡汉三带着小花Post参数回来了!"
}
}


]
写回答

1回答

大周

2020-02-07

断言失败了。 你debug一下,看看在哪一步乱的。 断点打在断言上一行代码。 

0
0

Java接口自动化测试实战,搞定理论基础+典型应用场景

打破传统测试用例设计方法,搞懂基于TestNG的接口自动化测试技术

2086 学习 · 920 问题

查看课程