1、依賴
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency>
2、請求步驟
- 使用幫助類HttpClients創建CloseableHttpClient對象.
- 基於要發送的HTTP請求類型創建HttpGet或者HttpPost實例.
- 使用addHeader方法添加請求頭部,諸如User-Agent, Accept-Encoding等參數.
- 可調用HttpGet、HttpPost共同的setParams(HetpParams params)方法來添加請求參數;對於HttpPost對象而言,也可調用setEntity(HttpEntity entity)方法來設置請求參數。
- 通過執行此HttpGet或者HttpPost請求獲取CloseableHttpResponse實例
- 從此CloseableHttpResponse實例中獲取狀態碼,錯誤信息,以及響應頁面等等.
- 釋放連接。無論執行方法是否成功,都必須釋放連接
3、get
public void httpGet() { CloseableHttpClient httpclient = HttpClients.createDefault(); try { // 創建httpget. HttpGet httpget = new HttpGet("http://www.baidu.com/"); System.out.println("executing request " + httpget.getURI()); // 執行get請求. CloseableHttpResponse response = httpclient.execute(httpget); try { // 獲取響應實體 HttpEntity entity = response.getEntity(); // 打印響應狀態 System.out.println(response.getStatusLine()); if (entity != null) { // 打印響應內容長度 System.out.println("Response content length: " + entity.getContentLength()); // 打印響應內容 System.out.println("Response content: " + EntityUtils.toString(entity)); } } finally { response.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 關閉連接,釋放資源 try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } }
4、post
public static String httpPost(String host, int port, byte[] buf) { CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse httpResponse = null; BufferedReader reader = null; StringBuffer response = new StringBuffer(); try { String url = "http://" + host + ":" + port; HttpPost httpPost = new HttpPost(url); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(6000).setConnectTimeout(6000).build();//設置請求和傳輸超時時間 httpPost.setConfig(requestConfig); httpPost.addHeader("User-Agent", "Mozilla/5.0"); ByteArrayEntity entity = new ByteArrayEntity(buf); httpPost.setEntity(entity); httpResponse = httpClient.execute(httpPost); reader = new BufferedReader(new InputStreamReader( httpResponse.getEntity().getContent())); String inputLine; while ((inputLine = reader.readLine()) != null) { response.append(inputLine); } }catch (Exception var){ var.printStackTrace(); }finally { if(reader != null){ reader.close(); } if(httpResponse != null){ httpResponse.close(); } httpClient.close(); } return response.toString(); }