天天看點

HttpClient之get請求傳回cookie資訊+攜帶這個cookie通路get接口

一.moco架構mock接口資訊

[
  {
    "description": "這是一個能傳回cookies資訊的get請求",
    "request": {
      "uri": "/getCookies",
      "method": "get"
    },
    "response": {
      "cookies": {
        "login": "true"
      },
      "text": "成功擷取到cookies資訊啦"

    }
  },
  {
    "description": "這是一個攜帶cookie的get請求",
    "request": {
      "uri": "/get/with/cookie",
      "method": "get",
      "cookies": {
        "login": "true"
      }
    },
    "response": {
      "text": "這是一個需要攜帶cookie的才能通路的get請求"
    }
  }
]
           

二.application.properties配置檔案資訊

test.url=http://localhost:8080
getCookies.uri=/getCookies
test.get.with.cookies=/get/with/cookie

           

三.編寫testNG測試方法

package com.course.httpclient.cookies;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

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

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 目光定晴天
 * @Date: 2021/6/5 11:14
 * @Description:
 */
public class MyCookiesForGet {
    private String url;
    private ResourceBundle bundle;
    //用來存儲cookies資訊的變量
    private CookieStore cookieStore;

    //在測試方法執行前加載配置檔案
    @BeforeTest
    public void beforeTest(){
        //如何讀取配置檔案?---java.util.ResourceBundle,隻需要傳參為配置檔案的字首即可
        bundle = ResourceBundle.getBundle("application", Locale.CHINA);
        url = bundle.getString("test.url");
    }
  
    //新版httpclient4.5.2
    @Test
    public void testGetCookies() throws IOException {
        //從配置檔案拼接測試的URL
        String uri;
        String testUrl;
        uri = bundle.getString("getCookies.uri");
        testUrl = this.url + uri;

        //擷取get方法
        HttpGet get = new HttpGet(testUrl);

        //建立cookiestore
        CookieStore cookieStore = new BasicCookieStore();

        //建立CloseableHttpClient對象,同時設定cookiestore
        CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

        //初始化response對象和正文響應字元串為null
        CloseableHttpResponse response = null;
        String result = null;
        //執行get方法
        try{
            response = client.execute(get);
            //為響應資料指定utf-8格式
            result = EntityUtils.toString(response.getEntity(),"utf-8");
            System.out.println(result);

            //擷取cookiestore,為全局變量cookieStore指派
            this.cookieStore = cookieStore;

            //列印輸出
            List<Cookie> cookieList = this.cookieStore.getCookies();
            for (Cookie c:
                    cookieList) {
                System.out.println("cookie name=" + c.getName() + ";cookie value=" + c.getValue());
            }

        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //擷取cookies資訊(HttpClient無法擷取,隻能通過DefaultHttpClient),
            //故需要修改DefaultHttpClient client = new DefaultHttpClient();
//        CookieStore cookieStore = client.getCookieStore();
//        this.cookieStore = client.getCookieStore();
//        List<Cookie> cookieList =  cookieStore.getCookies();
//        List<Cookie> cookieList = this.cookieStore.getCookies();
//        for (Cookie c:
//                cookieList) {
//            System.out.println("cookie name=" + c.getName() + ";cookie value=" + c.getValue());
//        }


    }
    @Test(dependsOnMethods = {"testGetCookies"})
    public void testGetWithCookies() throws IOException {
        //1.拼接URL
        String uri = bundle.getString("test.get.with.cookies");
        String testUrl = this.url + uri;

        //2.建立get請求對象 + 建立client對象,設定cookie + 建立response對象
        HttpGet get = new HttpGet(testUrl);
        CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(this.cookieStore).build();
        CloseableHttpResponse response = null;

        //3.執行get方法擷取response,擷取狀态碼,擷取響應資料
        try {
            //執行get方法
            response = client.execute(get);
            //擷取狀态碼
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println("statusCode is :" + statusCode);

            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity, "utf-8");
                System.out.println("請求接口成功");
                System.out.println("the result is :" + result);
            }else {
                System.out.println("請求接口失敗");
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                response.close();
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
  
}

           

四.啟動服務,測試運作

HttpClient之get請求傳回cookie資訊+攜帶這個cookie通路get接口

繼續閱讀