在做http接口测试的时候,老是要做一大堆的参数和值,整个界面看着相当别扭,于是就把参数部分组合放到一个方法中,把执行放到一个方法中,主函数就只要获取response字符串做处理做断言就好了,这样这个代码看上去清爽多了,这里用到了httpclient、dom4j、testng的jar包。
网站建设哪家好,找成都创新互联!专注于网页设计、网站建设、微信开发、微信小程序定制开发、集团企业网站建设等服务项目。为回馈新老客户创新互联还提供了秦淮免费建站欢迎大家使用!
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.testng.AssertJUnit;
public class HttpInterfaceTest {
private static String url;
private static String[][] keyVlaueList = {{"cdkey","6SDK"},{"password","160489"}}; //根据需要自定义接口参数个数及参数值
private static List
private static String responseEntiy;
/**
* 组装请求参数
* @param keyVlaueList
*/
public static List
for(int i = 0;i { postPara.add(new BasicNameValuePair(keyVlaueList[i][0],keyVlaueList[i][1])); } return postPara; } /** * 获取接口返回字符串 * @param url */ public static String getResponse(String url){ try { postPara = getPostPara(keyVlaueList); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost post = new HttpPost(url); post.setEntity(new UrlEncodedFormEntity(postPara)); CloseableHttpResponse response = httpclient.execute(post); HttpEntity entiyResponse = response.getEntity(); responseEntiy = EntityUtils.toString(entiyResponse).trim(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }catch (DocumentException e) { e.printStackTrace(); } return responseEntiy; } public static void main(String[] args){ url = "http://xxxxxxx/querybalance.action"; responseEntiy = getResponse(url); //获取的字符串:responseEntiy = //根据接口返回的字符类型做相应的解析,自由发挥! try { Document document = DocumentHelper.parseText(responseEntiy); Element rootElement = document.getRootElement(); Element nodeElement = rootElement.element("error"); String errorString = nodeElement.getTextTrim(); if (!errorString.equals("0")){ AssertJUnit.fail(responseEntiy); } }catch (DocumentException e) { e.printStackTrace(); } } }
标题名称:HttpClient做接口测试时自定义参数长度
文章分享:http://cxhlcq.com/article/ijdphe.html