http访问接口自动化测试,函数封装


封装方法get和post

package PublicClass;



import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.fluent.Response;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.omg.CORBA.portable.RemarshalException;


public class HttpClass {
/*
* urlEncodeFormEntity实例将会使用URL编码来编码参数
* 生成内容如下:param1=value1&param2=value2
*/

public static String  get(String url,Map<String,String>params) throws IOException {
String result="";
CloseableHttpClient httpClient=null;
HttpGet httpget=null;
try {
// 创建默认的httpClient实例. 
httpClient=HttpClients.createDefault();
RequestConfig rc=RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
String ps="";
//对map的遍历
for(String pKey:params.keySet()){
//根据ps判断是否为空,走if,如果为空,不执行,不为空,执行
if(!"".equals(ps)){
ps=ps+"&";
}
ps=pKey+"="+params.get(pKey);//带参拼凑
}
//拼接url
if(!"".equals(ps)){
url=url+"?"+ps;
}
httpget=new HttpGet(url);
httpget.setConfig(rc);
//调用httpclient响应函数
CloseableHttpResponse response=httpClient.execute(httpget);
HttpEntity httpEntity=response.getEntity();
System.out.print(EntityUtils.toString(httpEntity,"utf-8"));
result=EntityUtils.toString(httpEntity,"utf-8");
result="status="+response.getStatusLine().getStatusCode()+"&&"+"body="+result;
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(httpget !=null){
httpget.releaseConnection();
}
if(httpClient !=null){
httpClient.close();
}
} catch ( Exception e) {
e.printStackTrace();
}
}
return result;
}
//不带参数的post请求
public static  String LsusbPost(String url,Map<String, String>heaers) {
String result="";
CloseableHttpClient httpclient=null;
HttpPost httpPost=null;
try {
httpclient=HttpClients.createDefault();
RequestConfig rc=RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
httpPost=new HttpPost(url);
httpPost.setConfig(rc);
//创建参数队列


List<NameValuePair> formparams = new ArrayList<NameValuePair>();
for(String pKey:heaers.keySet()){
formparams.add(new BasicNameValuePair(pKey, heaers.get(pKey)));
}
httpPost.setEntity(new UrlEncodedFormEntity(formparams));
CloseableHttpResponse response=httpclient.execute(httpPost);
org.apache.http.HttpEntity httpEntity=response.getEntity();
System.out.println(EntityUtils.toString(httpEntity,"utf-8"));
result=EntityUtils.toString(httpEntity,"utf-8");
result="status="+response.getStatusLine().getStatusCode()+"&&"+"body="+result;

} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(httpPost!=null){
httpPost.releaseConnection();
}
if(httpclient!=null){
httpclient.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
//提交表单post
public static  String FormPost(String url,Map<String, String>body,Map<String, String>heaers) {
String result="";
CloseableHttpClient httpclient=null;
HttpPost httpPost=null;
try {
httpclient=HttpClients.createDefault();
RequestConfig rc=RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
httpPost=new HttpPost(url);
httpPost.setConfig(rc);
httpPost.addHeader("Content-type","application/x-www-form-urlencoded");
for(String pKey:heaers.keySet()){
httpPost.addHeader(pKey, heaers.get(pKey));
}
//创建参数队列


List<NameValuePair> formparams = new ArrayList<NameValuePair>();
for(String pKey:body.keySet()){
formparams.add(new BasicNameValuePair(pKey, body.get(pKey)));
}
httpPost.setEntity(new UrlEncodedFormEntity(formparams));
CloseableHttpResponse response=httpclient.execute(httpPost);
org.apache.http.HttpEntity httpEntity=response.getEntity();
//System.out.println(EntityUtils.toString(httpEntity,"utf-8"));
//EntityUtils.toString只能用一次,否则抛异常
result=EntityUtils.toString(httpEntity,"utf-8");
result="status="+response.getStatusLine().getStatusCode()+"&&"+"body="+result;

} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(httpPost!=null){
httpPost.releaseConnection();
}
if(httpclient!=null){
httpclient.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}


}

Junit测试代码:

package JunitTest;


import static org.junit.Assert.*;


import java.util.HashMap;
import java.util.Map;


import org.junit.After;
import org.junit.Before;
import org.junit.Test;


import PublicClass.HttpsClass;


public class demo {
    
@Before
public void setUp() throws Exception {
}


@After
public void tearDown() throws Exception {
}


@Test
public void test() {
String url_login="http://tspdemo.changan.com.cn/appserver/api/user/login";
HttpsClass http=new HttpsClass();
Map<String, String> body=new HashMap<String, String>();
Map<String, String> headers=new HashMap<String, String>();
body.put("phone","18375806076");
body.put("password","123456@");
String result=http.FormPost(url_login, body, headers);
System.out.println(result);

}


}



结果:status=200&&body={"success":true,"code":0,"data":{"userId":"f1979eb99187424da99e8ad764addb8f","uuid":null,"openId":"f1979eb99187424da99e8ad764addb8f","tenantId":"","userName":"``````","userNickname":null,"userFullname":"测试","mobile":"18375806076","contactsName":"","contactsMobile":"","countryId":"1000000000","country":"中国","provinceId":null,"province":"","cityId":null,"city":"","distId":null,"dist":"","community":"","status":"1","gender":"f","password":null,"birthday":"2013-05-01","email":"1119864992@qq.com","address":"","telephone":"","idcardType":"OTHERLICENCE","idcard":"snsnjsnsns","faceImg":"c0047798-8a1d-4b54-91da-934e7a3888fd","registerTime":"2017-02-14 09:16:07.0","activeTime":null,"source":"carbondApp","lastLoginTime":"2017-07-13 17:47:37.0","deleted":0,"locked":0,"token":"ZaO9NFhB9Y5g901uMFSm8AE66CtYUuob","brandName":null,"carId":null,"imUserId":"9fec6a56-bcaa-4749-85b8-01121a7b0dd2","imPassWord":"7781e954-14ed-4e4d-b543-e1fefe4ba3d2","plateNumber":null,"cycid":"","cycuid":"","sycid":"","sycuid":"","authenticationType":null},"msg":""}

要想全自动化:请在代码中添加Junit断言

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值