DefaultHttpClient 获取cookie信息

HttpClient类本身是不能获取cookie信息的,因此需要使用DefaultHttpClient 。

因为store.getCookies();获取cookie返回信息是List<Cookie>,因此为了获取cookie信息需要遍历list集合。本文使用的for循环遍历list集合。

java代码如下

package com.course.httpclient.cookies;

import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
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.BeforeTest;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;

public class MyCookieForGet {

    private String url;
    private ResourceBundle bundle;//用于读取配置文件

    @BeforeTest
    public void beforeTest() {

        bundle = ResourceBundle.getBundle("application", Locale.CHINA);
        //上行代码用于读取配置文件,baseName和类在同一目录的resource文件中
        url = bundle.getString("test.url");
        //上行代码是获取配置文件中的域名
    }

    @Test
    public void test1() throws IOException {

        String result;
        String uri = bundle.getString("getCookies.uri");
        //以上代码是获取配置文件中的getCookies.uri对应的路径
        String testurl = this.url + uri;
        HttpGet get = new HttpGet(testurl);
        System.out.println("这是testurl的地址" + testurl);
//        HttpClient client = new DefaultHttpClient(); HttpClient无法获取cookie信息
        DefaultHttpClient client = new DefaultHttpClient();
        //创建HttpClient对象,用于执行get请求
        HttpResponse response = client.execute(get);
        System.out.println("这是response的值" + response);
        result = EntityUtils.toString(response.getEntity(), "utf-8");
        System.out.println(result);
        //以下代码是获取cookie信息
        CookieStore store = client.getCookieStore();
        List<Cookie> cookkielist = store.getCookies();
        for (Cookie cookie : cookkielist) {
            String name = cookie.getName();
            String value = cookie.getValue();
            System.out.println("cookie name="+name+"  cookie value="+value);
        }


    }

}

接口信息配置文件application.properties如下

test.url=http://127.0.0.1:8888
getCookies.uri=/getCookies
login=/login

moco模拟接口信息如下

[
  {
    "description": "这是一个会返回cookies信息的get请求",
    "request": {
      "uri": "/getCookies",
      "method": "get"
    },
    "response": {
      "headers": {
        "Content-Type": "text/html;charset=gbk"
      },
      "cookies": {
        "login": "111111",
        "status": "1000"

      },
      "text": "恭喜你获得cookies信息成功"
    }
  }
]

猜你喜欢

转载自www.cnblogs.com/linxinmeng/p/12615061.html