前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >HttpClient测试框架

HttpClient测试框架

作者头像
yuanyuan
发布2019-09-02 15:37:50
1.1K0
发布2019-09-02 15:37:50
举报
文章被收录于专栏:小满

HttpClient是模拟Http协议客户端请求的一种技术,可以发送Get/Post等请求。 所以在学习HttpClient测试框架之前,先来看一下Http协议请求,主要看请求头信息。

如何查看HTTP协议请求头信息: 打开浏览器-->输入任意一个网址-->按下F12 打开开发者工具-->Network-->刷新页面,可以在Network看到有Get或者post请求的URL,点击URL,可以看到该请求的Header/Cookies/Response等信息

例如我们打开www.baidu.com,查看它某个请求的信息,如下:

常用的请求头和响应头信息解释:

下面通过一个简单的例子学习HttpClient

代码语言:javascript
复制
import java.io.IOException;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.testng.annotations.Test;

public class MyHttpClient {

    @Test
    public void test1() {
        String result;
        HttpGet get = new HttpGet("http://localhost:8888/getCookies");
        DefaultHttpClient client = new DefaultHttpClient();
        try {
            HttpResponse response = client.execute(get);
            result = EntityUtils.toString(response.getEntity());
           
            CookieStore cookieStore =   client.getCookieStore();
            List<Cookie> cookies =cookieStore.getCookies();
            System.out.println(cookies.size());
            for(Cookie c :cookies) {//get Cookies info
                System.out.println(c.getName() + ":" + c.getValue());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Run TestNG Test, 可以看到返回的result是HTML源码。这个是通过HttpClient Get请求方法实现的简单例子。下面结合Mock模拟数据,学习如何使用HttpClient。

Mock一个返回Cookies信息的请求:

代码语言:javascript
复制
{
   "description":"This get request with cookies return",
   "request":{
       "uri":"/getCookies",
       "method":"get"
   },
   "response":{
       "cookies":{
         "login":"true"
       },
       "text":"This is response with cookies"
   }
  }

具体如何Mock数据可以参考上一篇文章《Mock接口平台Moco学习》.

我们已经知道如何从服务端获取 Cookie信息了,那下一步学习客户端如何使用拿到的Cookie信息。

首先在Mock一个接口,这是携带/getCookies 接口返回的Cookies信息Get请求的接口:

代码语言:javascript
复制
{
   "description":"This is Get request with cookies",
   "request":{
       "uri":"/get/with/cookies",
       "method":"get",
       "cookies":{
          "login":"true"
       }
   },
   "response":{
       "text":"This is response for get request with cookies"
   }
 }

完整的代码:

代码语言:javascript
复制
import java.io.IOException;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.testng.annotations.Test;

public class MyHttpClient {
    private CookieStore cookieStore;

    @Test
    public void test1() {
        String result;
        HttpGet get = new HttpGet("http://localhost:8888/getCookies");
        DefaultHttpClient client = new DefaultHttpClient();
        try {
            HttpResponse response = client.execute(get);
            result = EntityUtils.toString(response.getEntity());
            System.out.println("result=" + result);
            cookieStore = client.getCookieStore();
            List<Cookie> cookies = cookieStore.getCookies();
            System.out.println(cookies.size());
            for (Cookie c : cookies) {
                System.out.println(c.getName() + ":" + c.getValue());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test(dependsOnMethods = { "test1" })
    public void testGetWithCookie() {
        HttpGet get = new HttpGet("http://localhost:8888/get/with/cookies");
        DefaultHttpClient client = new DefaultHttpClient();
        // Set cookie info
        client.setCookieStore(cookieStore);
        try {
            HttpResponse response = client.execute(get);
            // get response status
            int statusCode = response.getStatusLine().getStatusCode();
            // statusCode = 200 / 404 / 502.....
            System.out.println("Status = " + statusCode);
            if (statusCode == 200) {
                // Success
                String result = EntityUtils.toString(response.getEntity());
                System.out.println("result=" + result);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

HttpClient Post请求的实现:

首先还是Mock一个post请求

代码语言:javascript
复制
{ 
   "description":"This is Post request with cookies",
   "request":{
       "uri":"/post/with/cookies",
       "method":"post",
       "cookies":{
          "login":"true"
       },
       "json":{
           "name":"zhangsan",
           "age":"18"
       }
   },
   "response":{
       "status":200,
       "json":{
          "zhangsan":"success",
           "status":"1"
       }
   }
  }

完整的Post请求代码:

代码语言:javascript
复制
import java.io.IOException;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.Test;

public class MyCookiesForPost {
    private CookieStore cookieStore;

    @Test
    public void test1() {
        String result;
        HttpGet get = new HttpGet("http://localhost:8888/getCookies");
        DefaultHttpClient client = new DefaultHttpClient();
        try {
            HttpResponse response = client.execute(get);
            result = EntityUtils.toString(response.getEntity());
            System.out.println("result=" + result);
            cookieStore = client.getCookieStore();
            List<Cookie> cookies = cookieStore.getCookies();
            System.out.println(cookies.size());
            for (Cookie c : cookies) {
                System.out.println(c.getName() + ":" + c.getValue());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    @Test(dependsOnMethods = { "test1" })
    public void testPostWithCookie() {
        //1. Define a client to excute
        //2. Define a post method
        //3. Add pamarater
        //4. Set request header info; set cookie inof
        //5. Execute
        //6. Get and handle Result
        //7. assert result
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://localhost:8888/post/with/cookies");
        JSONObject param = new JSONObject();
        param.put("name", "zhangsan");
        param.put("age", "18");
        StringEntity entity = new StringEntity(param.toString(),"utf-8");
        post.setEntity(entity);
        post.addHeader("content-type", "application/json");
        client.setCookieStore(cookieStore);
        try {
           HttpResponse response = client.execute(post);
            String  result = EntityUtils.toString(response.getEntity());
            System.out.println("result=" + result);
            JSONObject object = new JSONObject(result);
            System.out.println("zhangsan=" + object.getString("zhangsan"));
            System.out.println("status=" + object.getString("status"));
            String actualResult = object.getString("zhangsan");
            Assert.assertEquals(actualResult,"success");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

代码优化: 在实际的测试过程当中,我们一般不会直接将请求地址写在请求对象当中。而是定义在配置文件中,然后在代码中引用。具体用法如下。

创建一个.properties文件,如config.properties:

代码语言:javascript
复制
test.url=http://localhost:8888

然后在代码中读取该config.properties,并获取相应的地址:

代码语言:javascript
复制
    private ResourceBundle bundle;
    private String url;
   
    @BeforeTest
    public void beforeTest() {
        bundle = ResourceBundle.getBundle("config");
        url = bundle.getString("test.url");
    }

以上是HttpClient的常见用法和其中一个优化方案。

如果喜欢作者的文章,请关注"写代码的猿"订阅号以便第一时间获得最新内容。本文版权归作者所有,欢迎转载.

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-05-10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云开发 CLI 工具
云开发 CLI 工具(Cloudbase CLI Devtools,CCLID)是云开发官方指定的 CLI 工具,可以帮助开发者快速构建 Serverless 应用。CLI 工具提供能力包括文件储存的管理、云函数的部署、模板项目的创建、HTTP Service、静态网站托管等,您可以专注于编码,无需在平台中切换各类配置。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档