private CloseableHttpClient httpClient = null;
@BeforeClass
public void setUpBeforeClass() {
// 通过这个方法创建的httpclient,只能手工模拟重定向过程:即先发起post请求,然后发起get请求
// httpClient = HttpClients.createDefault();
// 通过这个方法创建的httpclient,设置自动跟随重定向
httpClient = HttpClients.custom()
setRedirectStrategy(new LaxRedirectStrategy()).build();
}
@AfterClass
public void tearDownAfterClass() throws IOException {
httpClient.close();
}
/**
* 如何利用httpclient框架发送get请求
*
* @throws ClientProtocolException
* @throws IOException
*/
@Test
public void getTest() throws ClientProtocolException, IOException {
HttpGet httpGet = new HttpGet(
"http://101.200.167.51:8080/http/method?
username=yankunpeng&pwd=yankunpeng111&cars=volvo");
CloseableHttpResponse res = httpClient.execute(httpGet);
try {
// 获得状态行的状态码的信息
int statusCode = res.getStatusLine().getStatusCode();
System.out.println(statusCode);
// 获得响应的http
String resBody = EntityUtils.toString(res.getEntity());
// body部分
System.out.println(resBody);
} finally {
res.close();
}
}