首页 > Web开发 > 详细

HttpClient发送get请求

时间:2021-08-13 14:40:16      阅读:11      评论:0      收藏:0      [点我收藏+]
//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);
}

HttpClient发送get请求

原文:https://www.cnblogs.com/fengfengw/p/15136134.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!