public class Httpclient_post {
private ResourceBundle bundle;
private String url;
private BasicCookieStore store;
//方法執行前先讀取resource文件夾下的application文件中的url參數
@BeforeMethod
public void get_url(){
bundle =ResourceBundle.getBundle("application", Locale.CHINA);
url = bundle.getString("test.url");
}
//獲取cookie
@Test
public void testGetCookies_read() throws IOException {
String result;
String uri = bundle.getString("getCookies.url");
String testUri = this.url+uri;
this.store = new BasicCookieStore();
//獲取響應
HttpGet get = new HttpGet(testUri);
CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(store).build();
HttpResponse response = client.execute(get);
result = EntityUtils.toString(response.getEntity(),"utf-8");
System.out.println(result);
//獲取cookie
List<Cookie> cookies = store.getCookies();
for (Cookie cookie :cookies
) {
String name = cookie.getName();
String value = cookie.getValue();
System.out.println("cookie: key= "+name +",name="+value);
}
}
//獲取cookie並發送請求
//依賴讀取cookie的方法,cookie存放在store中
@Test(dependsOnMethods ={"testGetCookies_read"} )
public void getPost_cookie() throws IOException {
//獲取請求url
String ur = url+bundle.getString("test.get.with.cookies.post");
System.out.println(ur);
HttpPost post = new HttpPost(ur);
CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(store).build();
//設置請求頭信息
post.setHeader("content-type","application/json");
//設置jsong格式的請求參數
JSONObject param = new JSONObject();
param.put("name","hu");
param.put("age","18");
//將請求參數添加到方法中
StringEntity entity = new StringEntity(param.toString());
post.setEntity(entity);
//存貯響應結果
String result;
CloseableHttpResponse response = client.execute(post);
//獲取響應結果
result = EntityUtils.toString(response.getEntity());
System.out.println(result);
//處理結果,判斷結果是否符合預期
//將響應的結果字符串轉換成json
JSONObject restjson = new JSONObject(result);
String success = (String) restjson.get("gg");
String status = (String) restjson.get("status");
Assert.assertEquals("success",success);
Assert.assertEquals("1",status);
}
}