当自己写完接口后,一般会先自测一下, 以免联调时千疮百孔,耽误进度和降低自我形象。自测接口可以自己写单元测试测试一下,也可以使用第三方工具模拟测试一下,比如postman。
方案1 postman测试
postman自行网上搜索下载一个就行,不需要安装解压出exe即可,放本地某个目录下然后发送快捷方式至桌面即可。打开postman如下
如上椭圆圈出的params无需填写,毕竟我们一般是测post请求(因为get请求就是url后面拼接参数直接在浏览器地址栏请求即可无需多此一举了)。post请求主要填写三个地方,目标地址、headers(请求头,数据格式)、body (请求报文)。
示例是给app端写的接口约定json格式,按需修改( 如果headers空着没写,则点击send按钮请求过去,可能会返回’'未知错误"、"系统异常"之类的,无法请求到action里面去。)。
目标地址、headers、body填写后点击绿色的send按钮即可, 下面会显示返回数据信息。
方案2 自己写单元测试
自行编写即可,给一个xml格式请求参考示例
package httpTest;
import java.io.IOException;
public class TestMain {
public static void main(String[] args) throws YGException, IOException {
String reqUrl = "http://192.168.1.2:8080/userlogin/";
StringBuffer xmlParam = new StringBuffer("<?xml version=\"1.0\" encoding=\"GBK\"?>");
xmlParam.append("<root>");
xmlParam.append("<userName>yulisao</userName>");
xmlParam.append("<password>123456</password>");
xmlParam.append("<reqTime>20201105121314</reqTime>");
xmlParam.append("<signstr>54364eee3weqweqwsfas</signstr>");
xmlParam.append("</root>");
sendhttpRequest(xmlParam.toString(), reqUrl);
}
private static String sendhttpRequest(String requestData, String requestUrl) {
String result = "";
HttpPost httpPost = new HttpPost(requestUrl);
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
StringEntity entity = new StringEntity(requestData, "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, "utf-8");
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(result);
return result;
}
}