HttpClient中的各种请求
生活随笔
收集整理的這篇文章主要介紹了
HttpClient中的各种请求
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一:什么是HttpClient?
主要是模擬瀏覽器發送請求給server,監聽響應信息,推斷返回結果的正確性怎樣,因為避開的瀏覽器的UI ,也就將瀏覽器中全部載入的時間(比方常常要載入圖片啊)都省掉了,所以這個運行效率相當高二. 使用HttpClient
1.get請求
@Testpublic 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);//關閉httpclientresponse.close();httpClient.close();}2.帶參數的get請求
@Testpublic 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);//關閉httpclientresponse.close();httpClient.close();}3.post請求
@Testpublic 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請求
@Testpublic 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();}總結
以上是生活随笔為你收集整理的HttpClient中的各种请求的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: postgres循环sql
- 下一篇: 作为大龄开发人员,敢问路在何方?