利用 Java 实现接口 POST 请求测试
我们在测试接口时最方便的一种就是借助接口测试工具,比如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格式。
支持分享! 楼主可以把相关需要用到的包也放到代码当中么????? 八戒你干嘛 发表于 2017-6-23 13:13
楼主可以把相关需要用到的包也放到代码当中么?????
忘记了,我这里主要用到了
import net.sf.json.JSONObject 包用于json定义用
还有就是下面这三个包用于http请求用
https://testerhome.com/uploads/photo/2017/315f7c2e-2f1d-439e-8da1-2fb8d3ee9782.png!large
页:
[1]