接口自测方法

当自己写完接口后,一般会先自测一下, 以免联调时千疮百孔,耽误进度和降低自我形象。自测接口可以自己写单元测试测试一下,也可以使用第三方工具模拟测试一下,比如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;
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值