使用HttpClient4实现API测试实战(1)

编程技术  /  houtizong 发布于 3年前   51
0、特别说明
1、声明:如需转载,请注明来自 http://cgs1999.iteye.com/;
2、测试API的多附件上传,请查阅
使用HttpClient4实现API测试实战(2)——多附件上传

1、引言
由于项目开发需要实现已有的API接口的测试,但API接口使用了token验证机制,使用soupui进行测试时,每次都需要先获取token,然后再进行登录,接着才能进行相关API接口的测试。显然后面的API接口测试是我们需要的,而获取token和登录都不是我们想要的,有没有办法跳过这两个步骤,直接进行API接口测试呢?

答案是肯定的,下面我们就使用HttpClient实现API测试进行实战。

2、新建测试项目
2.1 添加项目依赖
commons-beanutils-1.8.0.jarcommons-collections-3.2.1.jarcommons-lang-2.4.jarcommons-logging-1.0.4.jardom4j-1.6.1.jarezmorph-1.0.6.jarhttpclient-4.0.1.jarhttpcore-4.0.1.jar


2.2 新建HttpClient帮助类HttpClientUtil
public class HttpClientUtil {public static DefaultHttpClient httpClient = null;public static HttpClient getInstance() {if (httpClient == null) {httpClient = new DefaultHttpClient();}return httpClient;}public static void disconnect() {httpClient = null;}public static String doGet(String url) {return doGet(url, new ArrayList<BasicNameValuePair>());}public static String doGet(String url, List<BasicNameValuePair> data) {/* 建立HTTP Post连线 */HttpGet httpGet = new HttpGet(url);try {HttpResponse httpResponse = HttpClientUtil.getInstance().execute(httpGet);if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {return EntityUtils.toString(httpResponse.getEntity());} else {System.out.println("doGet Error Response: " + httpResponse.getStatusLine().toString());}} catch (Exception e) {e.printStackTrace();}return null;}public static String doPost(String url) {return doPost(url, new ArrayList<BasicNameValuePair>());}public static String doPost(String url, List<BasicNameValuePair> data) {/* 建立HTTP Post连线 */HttpPost httpPost = new HttpPost(url);try {// 发出HTTP request// httpPost.setEntity(new UrlEncodedFormEntity(data, HTTP.UTF_8));httpPost.setEntity(new UrlEncodedFormEntity(data, "UTF-8"));// 取得HTTP responseHttpResponse httpResponse = HttpClientUtil.getInstance().execute(httpPost);// 若状态码为200 okif (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 取出回应字串return EntityUtils.toString(httpResponse.getEntity());} else {System.out.println("doPost Error Response: " + httpResponse.getStatusLine().toString());}} catch (Exception e) {e.printStackTrace();}return null;}}


2.3 新建XML帮助类XmlUtil
public class XmlUtil {/** * 将xml格式的字符串转化成可以解析的Document对象 *  * @param xml * @return */public static Document parseXmlToDocument(String xml) {Document doc = null;if (xml != null && !xml.equals("")) {StringReader sr = new StringReader(xml);InputSource is = new InputSource(sr);DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();DocumentBuilder builder = null;try {builder = factory.newDocumentBuilder();doc = builder.parse(is);} catch (Exception e) {e.printStackTrace();}}return doc;}// 从xml文件中获取节点的值public static String getContentFromXml(String xml, String NodeName) {return getContentFromXml(xml, NodeName, 0);}public static String getContentFromXml(String xml, String NodeName, int index) {String value = "";try {Document doc = XmlUtil.parseXmlToDocument(xml);if (doc != null) {Node node = doc.getElementsByTagName(NodeName).item(index);if (node != null) {value = node.getFirstChild().getTextContent();}}} catch (Exception e) {return null;}return value;}}


2.4 新建API帮助类ApiUtil
public class ApiUtil {private static final String OAUTH_COMSUMER_KEY = "key";private static final String OAUTH_COMSUMER_SECRET = "password";private static final String API_URL = "http://localhost/api";private static String token = null;public static String getToken() {if (token == null) {token = accountToken(OAUTH_COMSUMER_KEY, OAUTH_COMSUMER_SECRET);}return token;}// Oauth的accountToken的获得public static String accountToken(String key, String secret) {List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(0);params.add(new BasicNameValuePair("oauth_consumer_key", key));params.add(new BasicNameValuePair("oauth_consumer_secret", secret));String xml = HttpClientUtil.doPost(API_URL + "/accountToken", params);if (hasText(xml)) {if (xml.indexOf("errorCode") == -1) {return XmlUtil.getContentFromXml(xml, "accountToken");} else {// 存在错误信息则返回nullreturn null;}} else {return null;}}// 用户登录接口public static boolean login(String username, String password) {return login(username, password, null);}public static boolean login(String username, String password, String userType) {List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(0);params.add(new BasicNameValuePair("account_token", getToken()));params.add(new BasicNameValuePair("username", username));params.add(new BasicNameValuePair("password", password));if (userType != null) {params.add(new BasicNameValuePair("userType", userType));}String xml = HttpClientUtil.doPost(API_URL + "/login", params);if (!hasText(xml)) {return false;}if (xml.indexOf("errorCode") == -1) {return true;} else {return false;}}private static boolean hasText(String strText) {return strText != null && !"".equals(strText);}}


2.5 ApiUtil中增加测试方法
public static void main(String[] argus) {System.out.println(ApiUtil.getToken());ApiUtil.login("[email protected]", "password");}


2.6 运行测试
运行测试类后,出现“HTTP/1.1 302 Moved Temporarily”错误,但类似的代码在浏览器中执行没有问题,这究竟是什么原因造成?该如何解决呢?

3、302错误的原因及解决方法
(1)SOSO问问中“HTTP/1.1 302 Moved Temporarily”的内容如下:
引用

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!

留言需要登陆哦

技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成

网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];

      订阅博客周刊 去订阅

文章归档

文章标签

友情链接

Auther ·HouTiZong
侯体宗的博客
© 2020 zongscan.com
版权所有ICP证 : 粤ICP备20027696号
PHP交流群 也可以扫右边的二维码
侯体宗的博客