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); } }