接口测试HttpClient实践20150925

 

         用了工具做接口测试,但是对于加密数据和结果的比对,以及批量数据读取,回头还是觉得代码来更方便灵活,从excle中读取数据,构成参数,发请求,并获取返回结果和预期值比较,并将结果输出程报告,可以深入做成框架,用来还算是比较方便的,就研究了下httpclient,刚刚起步,还不是很熟练,以下是实战,不懂不要紧,先跟着练习几次,慢慢就理解了:

1、在eclipse中新建java工程,添加jar包

image

2、添加httpclient的jar包

image

3、编写代码,一般我会写两个一个是get请求的,一个是post请求的,我这里写了一个post,里面包含了将数据存取文件中,和加密解密的方法:

代码区:

/**
     * Post请求
     *
     * @param url
     * @throws IOException
     */
    public static void httpClientPostMethod(String url) throws IOException {
        // 1、创建 HttpClient 的实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // post请求
        HttpPost httpPost = new HttpPost(url);
        // 设置请求参数
        File file = new File(
                "C:/001myWorkspace/001工作/01移动平台/02 测试文档/03 用例梳理/James用例/V0.3版本/加密版/转义后/");
        File[] tempList = file.listFiles();// 该方法返回的是文件数组
        for (int i = 0; i < tempList.length; i++) {
            // 循环这个数组
            if (tempList[i].isFile()) {
                // 根据需要取出文件
                InputStream is = null;
                CloseableHttpResponse response = null;
                try {
                    // param 为参数,并url编码
                    String param = GetDataFromText.getData(tempList[i]
                            .toString());
                    StringEntity entity0 = new StringEntity(param);
                    // 设置请求头信息
                    entity0.setContentType("application/json");
                    httpPost.setEntity(entity0);
                    // 发送请求
                    response = httpClient.execute(httpPost);
                    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                        // 2、获取response的entity。
                        HttpEntity entity = response.getEntity();
                        // 3、获取到InputStream对象,并对内容进行处理
                        is = entity.getContent();
                        System.out.println(is);
                        // 返回的内容保存到文本
                        saveToFile("C:/001myWorkspace/tmp/", i + "test.xml", is);
                        // 获取结果,并解密
                        test.getResultFromTxt("C:/001myWorkspace/tmp/" + i
                                + "test.xml");
                    }
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } finally {
                    if (is != null) {
                        is.close();
                    }
                    if (response != null) {
                        response.close();
                    }
                }
            }
        }

    }

4、在main方法中调用,执行,并查看结果

image

posted @ 2015-09-25 15:34  黑夜小怪  阅读(1464)  评论(0编辑  收藏  举报