一:什麼是HttpClient?
主要是模擬瀏覽器發送請求給server,監聽響應信息,推斷返回結果的正確性怎樣,由於避開的瀏覽器的UI
,也就將瀏覽器中所有載入的時間(比方經常要載入圖片啊)都省掉了,因此這個運行效率至關高
二. 使用HttpClient
1.get請求
@Test
public void doGet() throws Exception {
//建立一個httpclient對象
CloseableHttpClient httpClient = HttpClients.createDefault();
//建立一個GET對象
HttpGet get = new HttpGet("http://www.sogou.com");
//執行請求
CloseableHttpResponse response = httpClient.execute(get);
//取響應的結果
int statusCode = response.getStatusLine().getStatusCode();
System.out.println(statusCode);
HttpEntity entity = response.getEntity();
String string = EntityUtils.toString(entity, "utf-8");
System.out.println(string);
//關閉httpclient
response.close();
httpClient.close();
}
2.帶參數的get請求
@Test
public void doGetWithParam() throws Exception{
//建立一個httpclient對象
CloseableHttpClient httpClient = HttpClients.createDefault();
//建立一個uri對象
URIBuilder uriBuilder = new URIBuilder("http://www.sogou.com/web");
uriBuilder.addParameter("query", "花千骨");
HttpGet get = new HttpGet(uriBuilder.build());
//執行請求
CloseableHttpResponse response = httpClient.execute(get);
//取響應的結果
int statusCode = response.getStatusLine().getStatusCode();
System.out.println(statusCode);
HttpEntity entity = response.getEntity();
String string = EntityUtils.toString(entity, "utf-8");
System.out.println(string);
//關閉httpclient
response.close();
httpClient.close();
}
3.post請求
@Test
public void doPost() throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
//建立一個post對象
HttpPost post = new HttpPost("http://localhost:8082/httpclient/post.html");
//執行post請求
CloseableHttpResponse response = httpClient.execute(post);
String string = EntityUtils.toString(response.getEntity());
System.out.println(string);
response.close();
httpClient.close();
}
4.帶參數的post請求
@Test
public void doPostWithParam() throws Exception{
CloseableHttpClient httpClient = HttpClients.createDefault();
//建立一個post對象
HttpPost post = new HttpPost("http://localhost:8082/httpclient/post.html");
//建立一個Entity。模擬一個表單
List<NameValuePair> kvList = new ArrayList<>();
kvList.add(new BasicNameValuePair("username", "zhangsan"));
kvList.add(new BasicNameValuePair("password", "123"));
//包裝成一個Entity對象
StringEntity entity = new UrlEncodedFormEntity(kvList, "utf-8");
//設置請求的內容
post.setEntity(entity);
//執行post請求
CloseableHttpResponse response = httpClient.execute(post);
String string = EntityUtils.toString(response.getEntity());
System.out.println(string);
response.close();
httpClient.close();
}