后台代码模拟postman实现多接口调用
1,使用场景
不用postman去测试接口。而是需要后台代码写在单元测试里。而传统的是根据单元测试用例去调用controller或者service(逻辑层代码)。如果有天发现,业务逻辑代码不见了。紧急需要调用接口,又没工具的情况下
请参考这个链接
http构建
2,模拟接口
1,get请求传参,header请求头校验。
2,post请求不传参,传对象。并且对象不是必须要传。不传对象时查询list所有。传对象requestbody里传。header请求头校验
3,远程接口调通
4,本地单元测试用例代码
做了小小处理因为EntityUtils。阿里巴巴的这个工具类有点坑。像toString方法一定走关闭流这个操作。导致get请求后无法再同一方法里掉post请求。
所以代码如下
package com.testfe;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.testfe.pojo.Student;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.*;
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestfeApplicationTests {
/**
* GET---有参测试 (方式一:手动在url后面加上参数)
*
* @date 2018年7月13日 下午4:19:23
*/
@Test
public void doGetTestWayTWO() {
// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 参数
StringBuffer params = new StringBuffer();
// post请求参数
//这里编码
/*try {*/
// 字符数据最好encoding以下;这样一来,某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)
// params.append("name=" + URLEncoder.encode("&", "utf-8"));
//params.append("&");
params.append("id=1");
/* } *//*catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}*/
// 创建Get请求
HttpGet httpGet = new HttpGet("http://你的远程地址:8090/SSM/getId" + "?" + params);
//创建Header
httpGet.setHeader("Content-Type","text/cmd");
httpGet.setHeader("Authorization","abcdefg");
httpGet.setHeader("app","com.ljs.pass");
// 响应模型
CloseableHttpResponse response = null;
try {
// 配置信息
RequestConfig requestConfig = RequestConfig.custom()
// 设置连接超时时间(单位毫秒)
.setConnectTimeout(5000)
// 设置请求超时时间(单位毫秒)
.setConnectionRequestTimeout(5000)
// socket读写超时时间(单位毫秒)
.setSocketTimeout(5000)
// 设置是否允许重定向(默认为true)
.setRedirectsEnabled(true).build();
// 将上面的配置信息 运用到这个Get请求里
httpGet.setConfig(requestConfig);
// 由客户端执行(发送)Get请求
try {
response = httpClient.execute(httpGet);
} catch (IOException e) {
e.printStackTrace();
}
// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
System.out.println("get请求响应状态为:" + response.getStatusLine());
if (responseEntity != null) {
System.out.println("get请求响应内容长度为:" + responseEntity.getContentLength());
byte[] bytes = EntityUtils.toByteArray(responseEntity);
System.out.println("====未做处理==="+bytes.toString());
/*
因为EntityUtils中的toString源码。调用则关闭流。不能满足我接下来调用post请求,
所以将它转为字节流。再转为字符串
*/
/*
调用字节输入流
*/
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
InputStreamReader inputStreamReader = new InputStreamReader(byteArrayInputStream);
BufferedReader br = new BufferedReader(inputStreamReader);
String s = null;
StringBuilder builder = new StringBuilder();
while((s=br.readLine())!=null){
builder.append(s);
}
String result = builder.toString();
System.out.println("get请求响应内容为:" + result );
//第二个接口post请求
// 创建Post请求
HttpPost httpPost = new HttpPost("http://你的远程地址:8090/SSM/getall");
/*
拿到name = “”的值
*/
JSONObject jsonObject = JSONObject.parseObject(result);
String data = jsonObject.get("data").toString();
JSONObject jsonObject1 = JSONObject.parseObject(data);
String name = jsonObject1.get("name").toString();
/*对象入参(可以传对象,参数也可不传)*/
Student student = new Student();
student.setName(name);
String jsonString = JSON.toJSONString(student);
StringEntity entity = new StringEntity(jsonString, "UTF-8");
// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
httpPost.setEntity(entity);
//创建Header
httpPost.setHeader("Content-Type","application/json");
httpPost.setHeader("Authorization","abcdefg");
httpPost.setHeader("app","com.ljs.pass");
// 响应模型
CloseableHttpResponse response2 = null;
// 由客户端执行(发送)Post请求
response2 = httpClient.execute(httpPost);
// 从响应模型中获取响应实体
HttpEntity responseEntity2 = response2.getEntity();
System.out.println("post响应状态为:" + response2.getStatusLine());
if (responseEntity2 != null) {
System.out.println("post响应内容长度为:" + responseEntity2.getContentLength());
System.out.println("post响应内容为:" + EntityUtils.toString(responseEntity2));
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}