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);
}
上一篇:记录core中GRPC长连接导致负载均衡不均衡问题一:查看源码,看创建过程


下一篇:ASP.NET Core扩展库