HttpClient发送get请求

HttpClient发送get请求//1.get请求无参数@TestpublicvoidtestGet()throwsIOException{Stringresult;HttpGetget=newHttpGet("http://www.baidu.com");HttpClientcli

大家好,欢迎来到IT知识分享网。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);
}

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/33432.html

(0)

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信