HTTP请求使用自定义cookie

  • Post author:
  • Post category:其他


目前需要在Jemeter中测试登录接口,接口设计的比较复杂,需要先从服务器中获取时间戳,通过时间戳来给密码加密,再请求登录,并且为了保持一致,获取时间戳时的cookie需要和请求登录时的cookie相同,否则登录不成功。

Jemeter接口测试需要先使用Java中编写代码,打包成jar包在Jemeter中运行。

首先引入依赖:

		<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.2.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.2.4</version>
        </dependency>

使用4.2.5版本,虽然比较老,但是有一个地方很好使。好了,先上代码

请求一:

DefaultHttpClient client = new DefaultHttpClient(new PoolingClientConnectionManager());
//HeaderUtil是自己写的设置请求头参数工具,无甚特殊
HeaderUtil headerUtil=new HeaderUtil();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = null;
httpPost.setHeaders(headerUtil.GetHeader());
httpResponse = client.execute(httpPost);

请求二:

HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = null;
DefaultHttpClient httpClient1 = new DefaultHttpClient();

//此处的client,为上部分定义的client
httpClient1.setCookieStore(client.getCookieStore());
httpClient1.getCookieStore();
httpResponse = httpClient1.execute(httpPost);

注意:目前只在2.4.5版本才能找到getCookieStore方法,此前尝试了一个新版本,需要自己手动设置cookie,所以就降为旧版本了。不过在之后,我又找到了另一个方法。附上代码:

//先从第一次请求返回的httpResponse 获取cookie,代码略

//开始手动拼装cookie
BasicClientCookie cookie = new BasicClientCookie("cookieName","cookieValue");
cookie.setPath("/");
cookie.setDomain("xx.xx.xx.xx");
cookie.setAttribute("domain", "xx.xx.xx.xx");
cookie.setAttribute("path", "/");
cookie.setAttribute("cookieName","cookieValue");
CookieStore cookieStore = new BasicCookieStore();
cookieStore.addCookie(cookie);

//设置httpClient与cookie
CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

这样也可以使用同样的cookie去访问接口啦!

如诸君有高见,请多多指教!



版权声明:本文为qq_39753413原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。