1. 程式人生 > 其它 >Java介面測試-post請求,使用httpClient獲取cookies+攜帶獲取的cookies訪問post介面

Java介面測試-post請求,使用httpClient獲取cookies+攜帶獲取的cookies訪問post介面

public class MyCookiesForPost {
    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");
    }
    @Test
    
public void test1() throws IOException { String getUrl = this.url +bundle.getString("getCookie.uri"); String result; cookieStore = new BasicCookieStore(); HttpGet get = new HttpGet(getUrl); 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 postUrl = this.url +bundle.getString("test.post.with.cookies"); // 宣告一個client物件,用來進行方法的執行並設定cookies資訊 CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(this.cookieStore).build(); // 宣告一個post方法 HttpPost httpPost = new HttpPost(postUrl); // 新增引數 JSONObject param = new JSONObject(); param.put("name", "huhansan"); param.put("sex", "nan"); // 設定請求頭資訊 httpPost.setHeader("content-type","application/json"); // 將引數資訊新增到方法中 StringEntity entity = new StringEntity(param.toString(),"utf-8"); httpPost.setEntity(entity); // 宣告一個物件用來儲存響應結果 String result; // 執行post方法 HttpResponse httpResponse = client.execute(httpPost); // 獲取響應結果 result = EntityUtils.toString(httpResponse.getEntity(),"utf-8"); System.out.println(result); // 判斷返回結果是否符合預期 // 將返回結果字串轉換成json物件 JSONObject resultJson = new JSONObject(result); // 獲取到結果值 String success = resultJson.getString("huhansan"); String status = resultJson.getString("status"); // 具體的判斷返回結果的值 Assert.assertEquals("success",success); Assert.assertEquals("1",status); } }