【一】HttpClient4.3.1簡單入門例項
阿新 • • 發佈:2019-02-19
1、先看一下示例程式碼
public class HttpClientTest { public static void main(String args[]) { //建立HttpClientBuilder HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); //HttpClient CloseableHttpClient closeableHttpClient = httpClientBuilder.build(); HttpGet httpGet = new HttpGet("http://www.gxnu.edu.cn/default.html"); System.out.println(httpGet.getRequestLine()); try { //執行get請求 HttpResponse httpResponse = closeableHttpClient.execute(httpGet); //獲取響應訊息實體 HttpEntity entity = httpResponse.getEntity(); //響應狀態 System.out.println("status:" + httpResponse.getStatusLine()); //判斷響應實體是否為空 if (entity != null) { System.out.println("contentEncoding:" + entity.getContentEncoding()); System.out.println("response content:" + EntityUtils.toString(entity)); } } catch (IOException e) { e.printStackTrace(); } finally { try {
//關閉流並釋放資源
closeableHttpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
以下內容來自HttpClient4.3.1 API文件:http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/overview-summary.html
2、HttpClientBuilder
HttpClientBuilder用於建立CloseableHttpClient例項。看了一下API文件,AbstractHttpClient、AutoRetryHttpClient、DefaultHttpClient等都被棄用了,使用HttpClientBuilder代替。
3、CloseableHttpClient
4、HttpGet
非執行緒安全;HttpGet有三個構造方法:HttpGet()、HttpGet(String uri)、HttpGet(URI uri)
5、HttpResponse
伺服器在接收和解釋請求之後返回一個HTTP響應資訊
Response = Status-Line *(( general-header | response-header | entity-header ) CRLF) CRLF [ message-body ]