无线测试技术-利用httpclient实现自动化测试

来源:互联网 发布:方正字体检测软件 编辑:程序博客网 时间:2024/05/02 10:40

在日常的页面自动化过程当中,经常遇到页面解析错误而导致脚本的成功率不高,从而导致回归的效果不甚理想。另一方面,PC端的web自动化工具不少,但是手机端呢,而且没有源码,怎么办?以之前做过的一个小说项目为背景简单的介绍如何利用httpClient实现自动化。(需要比较A小说站点和B、C站点对同一本小说的章节更新能力对比)
项目分析:

(1)A、B、C都是通过http的通信方式;
(2)A通过发送ajax请求,服务器返回的是json包;
(3)B、C服务器返回的是html文件;
有了输入、输出,问题就变得很简单了。实现过程:
(1)利用httpClient模拟请求
网上对httpClient4的使用说明有很多了。这里不详细介绍哈。下面贴一个简单的例子。http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2113252.html 

public static String[] httpReqAndRsp(String url)throws InterruptedException {        String resp = null;        HttpClient httpclient = new DefaultHttpClient();        HttpGet httpget = new HttpGet(url);        HttpResponse response;        HttpEntity entity = null;        try {           response = httpclient.execute(httpget);           entity = response.getEntity();//返回服务器响应            int statusCode = response.getStatusLine().getStatusCode();            if (statusCode != HttpStatus.SC_OK) {                System.err.println(“Method failed:” + response.getStatusLine());            }           if(statusCode == HttpStatus.SC_OK){                resp = EntityUtils.toString(entity);            }        } catch (IOException e) {           System.out.println(“IOException :”);            e.printStackTrace();        } finally {            httpget.releaseConnection();        }        return temp;    }

(2)    解析json包

public void updateTimeNovelReader(String response, String type) {        JSONObject jsonObject = JSONObject.fromObject(response);        try{                 JSONArray jsonArray = jsonObject.getJSONArray(“rows”);                 JSONObject obj = (JSONObject) jsonArray.get(0);                 String resourceid = (String) obj.get(“resourceid”);        } catch(JSONException e){                 e.printStackTrace();        }

(3)    解析html文件

public void updateTimeBookSky(String response)  {         TagNameFilter table = new TagNameFilter(“table”);         TagNameFilter tr = new TagNameFilter(“tr”);         TagNameFilter td = new TagNameFilter(“td”);         // 获取第3个table的内容         Node node_table = CommonOperation.tagParser(response, table, 2, charset);         if(null != node_table){                  String temp = node_table.toHtml();                  // 获取tr标签                  Node node_tr_bookname = CommonOperation.tagParser(temp, tr, 0, charset);                  if(node_tr_bookname ==null)                           return;                  String temp_node_tr_bookname = node_tr_bookname.toHtml();                  Node node_td_bookname = CommonOperation.tagParser(temp_node_tr_bookname, td, 0, charset);                  if(node_td_bookname ==null)                           return;                  }         }

        过程中遇到了不少问题:
(1)各类站点的返回结构不一致、html文件结构不一致,需要对每个站点重写脚本,导致脚本的成本高。
(2)Linux和windows对字符的编码不一致,需要转换,这个太坑爹了。Windows常用gbk,gb2132的编码方式,Linux常用utf-8的编码方式。如果以后再遇到编码的问题,建议增加配置项。

 

0 0