篇首推荐一篇简短精悍接口调用小文 传送门:https://blog.csdn.net/starkpan/article/details/77430569
一、测通接口
坑:
先做了后面工作,直到controller去调用时,才得到错误提示:非本地数据请合并成一条数据,这导致我需要修改方法去处理这些数据。如果一开始能用postman多测一些,并且仔细仔细研究传送过去的数据样式是怎样的,模拟一些数据等等,这样可以避免修改代码。
最好先仔细阅读参考手册
一般接口提供者都会提供接口调用参考手册,甚至是测试类,以此次案例为例:
- 测试基础地址:http://xxx.xx.xxx.xx:8080/xxxxx
- 接口访问地址 :基础地址/interface/xxxx/agent
- 通信协议:所有接口均通过 HTTP 进行通信
- 请求方法 :只支持 POST 请求
- 字符编码 :均使用 UTF-8 编码
- 参数格式 :所有请求参数和返回的参数均为 json 字符串。金额单位均为万元。
- 加密方式:将请求参数 json 字符串+密钥字符串,MD5 加密,将加密后的字符串,放在传递的 json 参数新增的 key 参数中。
①传递的参数为:{“data”:{“name”:”Tom”,”id”:”123”}}
②测试环境密钥为:A98Gdgksg8763uasiPP0(生产环境秘钥在资料中获取)
③传递参数+密钥字符串为: { “data”:{“name” :”Tom” ,”id”:”123”}} A98Gdgksg8763uasiPP0
④MD5 加密后的字符串为:FE43666F57CF301092448801C9CF5EC1
⑤最后传递的参数为: { “data”:{“name” :”Tom” ,”id” :”123”},”key”:” FE43666F57CF301092448801C9CF5EC1”} - 返回数据说明 :code:1 成功,0 失败 。message:错误信息
- 例子:
提交参数:
{ “data”: { “a”: “1”, “b”: “2”, “c”: “3” }, “listpro”: [ { “A”: “1”, “B”: “2” } ], “listlife”: [ { “Q”: “11”, “W”: “22” } ], “key”: “” }
POSTMAN 测起来!
测试类 测起来!main方法即可
public class TestUtils {
public static void main(String[] args) throws Exception{
String str = "{\"data\":{\"year\":2019,\"prre\":0,...},\"listlife\":[],\"listpro\":[{\"commre\":0,\"pred\":0,..} {\"comre\":0,\"pred\":0,...},...],\"key\":\"D01D230A35108950DD376BE362FFA61A\"}";
String url="http://xxx.xx.xxx.xx:8080/xxxxx";
HttpPost httpPost=new HttpPost(url);
Header header=new BasicHeader("Content-Type","application/json");
httpPost.addHeader(header);
HttpEntity httpEntity=new StringEntity(str);
httpPost.setEntity(httpEntity);
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
}).build();
CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).
setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
HttpResponse httpResponse=client.execute(httpPost);
//测试是否请求成功
int code=httpResponse.getStatusLine().getStatusCode();
String result="";
if (code == 200) {
result= EntityUtils.toString(httpResponse.getEntity());
}
System.out.println("result=="+result);
}
}
返回结果
result=={“result”:{“code”:“0”,“message”:“密钥比对失败,原因:key值不一致”}}