Java接口測試-get請求,使用httpClient獲取cookies+攜帶獲取的cookies訪問get接口


public class MyCookiesForGet {
    private String url;
    private ResourceBundle bundle;
    //用來存儲cookies信息的變量
    private CookieStore cookieStore;
    @BeforeTest
    public void beforeTest(){
        bundle = ResourceBundle.getBundle("application", Locale.CHINA);
        url = bundle.getString("test.url")+bundle.getString("getCookie.uri");
    }
    @Test
    public void test1() throws IOException {
        String result;
        cookieStore = new BasicCookieStore();
        HttpGet get = new HttpGet(this.url);
        CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        HttpResponse response = client.execute(get);
        result = EntityUtils.toString(response.getEntity(),"utf-8");
        System.out.println(result);
        // 獲取cookies信息
        List<Cookie> cookies = cookieStore.getCookies();
        for(Cookie cookie:cookies){
            String name = cookie.getName();
            String value = cookie.getValue();
            System.out.println("cookies key ="+name+",cookies value ="+value);
        }

    }
    @Test(dependsOnMethods = {"test1"})
    public void test2() throws IOException {
        String uri = bundle.getString("test.get.with.cookies");
        String testUrl = bundle.getString("test.url")+uri;
        CookieStore cookieStore = new BasicCookieStore();
        HttpGet httpGet = new HttpGet(testUrl);
        // 設置cookies信息
     //區別於上一個get請求client方法,這邊使用this.cookieStore是直接使用存儲的cookie
CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(this.cookieStore).build(); CloseableHttpResponse response = client.execute(httpGet); // 獲取響應的狀態碼 int statusCode = response.getStatusLine().getStatusCode(); System.out.println("statusCode = " + statusCode); if(statusCode == 200){ String result = EntityUtils.toString(response.getEntity(),"utf-8"); System.out.println(result); } } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM