1. 程式人生 > 其它 >HttpClient傳送get請求

HttpClient傳送get請求

//1.get請求無引數
@Test
public void testGet() throws IOException {
String result;
HttpGet get = new HttpGet("http://www.baidu.com");
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(get);
result = EntityUtils.toString(response.getEntity());
System.out.println(result);

}

//2.get請求獲取cookie
private String url;
private ResourceBundle bundle;
//用來儲存cookie資訊的變數
private BasicCookieStore store;
@BeforeTest
public void beforeTest(){
  
//讀取resource下application.properties檔案

bundle = ResourceBundle.getBundle("application",Locale.CHINA);
   url =  bundle.getString("test.url");
}
//獲取cookie,cookie儲存在store中

@Test
public void testGetCookies_read() throws IOException {
String result;
  //讀取resource下application.properties檔案中的獲取cookie的url
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);
}
}
//3.獲取cookie併發送請求
//依賴獲取cookie的test方法
@Test(dependsOnMethods ={"testGetCookies_read"} )
public void testGetwithCookies() throws IOException {
String uri = bundle.getString("test.get.with.cookies");
String testUri = this.url+uri;
System.out.println("url="+testUri);
HttpGet get = new HttpGet(testUri);
CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(store).build();
HttpResponse response = client.execute(get);
int status = response.getStatusLine().getStatusCode();
System.out.println("status= "+status);
String result= EntityUtils.toString(response.getEntity(),"utf-8");
System.out.println(result);
}