我们在测试接口时最方便的一种就是借助接口测试工具,比如 soapui,jmeter,火狐插件等……
而今天我这里用到的是用 java 代码实现接口 post 请求的测试,哈哈,估计网上很多人已经分享过了,我这里就作为自己的笔记记录下


public class postDemo {
    /**
     * 定义所需的变量
     */
    private static HttpClient httpClient = new DefaultHttpClient();
    private static HttpPost httppost;
    private static HttpResponse response;
    private HttpEntity entity;
    private String postResult = null;

    public static void main(String[] args) {

        String loginURL = "我们要测试的接口地址";
        // 创建一个httppost请求
        httppost = new HttpPost(loginURL);
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("mobile", "15627898765");
        jsonParam.put("password","e10adc3949ba59abbe56e057f20f883e");

        try {

            StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");// 解决中文乱码问题
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httppost.setEntity(entity);
            response = httpClient.execute(httppost); 
            String strResult = EntityUtils.toString(response.getEntity());
            System.out.println("查看返回的结果:" + strResult);


        } catch (Exception e) {
            e.printStackTrace();
        }

        httppost.releaseConnection();
    }
}

返回结果为:
{"isSuccess":true,"responseCode":0,"responseMsg":"请求成功","token":"c4cdf5116f6fc1d8fe80ea7d250db4bd"}

这里是 post 请求的,post 参数为 json 格式。


↙↙↙阅读原文可查看相关链接,并与作者交流