HttpClient程序包是一個實現了 HTTP 協議的客戶端編程工具包,要想熟練的掌握它,必須熟悉 HTTP協議。一個最簡單的調用以下:apache
import java.io.IOException; 服務器
import org.apache.http.HttpResponse; 網絡
import org.apache.http.client.ClientProtocolException; app
import org.apache.http.client.HttpClient; ssh
import org.apache.http.client.methods.HttpGet; 工具
import org.apache.http.client.methods.HttpUriRequest; 學習
import org.apache.http.impl.client.DefaultHttpClient;
public class Test {
public static void main(String[] args) {
// 核心應用類
HttpClient httpClient = new DefaultHttpClient();
// HTTP請求
HttpUriRequest request =
new HttpGet("http://localhost/index.html");
// 打印請求信息
System.out.println(request.getRequestLine());
try {
// 發送請求,返回響應
HttpResponse response = httpClient.execute(request);
// 打印響應信息
System.out.println(response.getStatusLine());
} catch (ClientProtocolException e) {
// 協議錯誤
e.printStackTrace();
} catch (IOException e) {
// 網絡異常
e.printStackTrace();
}
}
}
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
public class Test {
public static void main(String[] args) {
// 核心應用類
HttpClient httpClient = new DefaultHttpClient();
// HTTP請求
HttpUriRequest request =
new HttpGet("http://localhost/index.html");
// 打印請求信息
System.out.println(request.getRequestLine());
try {
// 發送請求,返回響應
HttpResponse response = httpClient.execute(request);
// 打印響應信息
System.out.println(response.getStatusLine());
} catch (ClientProtocolException e) {
// 協議錯誤
e.printStackTrace();
} catch (IOException e) {
// 網絡異常
e.printStackTrace();
}
}
}
若是HTTP服務器正常而且存在相應的服務,則上例會打印出兩行結果:
GET http://localhost/index.html HTTP/1.1
HTTP/1.1 200 OK
核心對象httpClient的調用很是直觀,其execute方法傳入一個request對象,返回一個response對象。使用httpClient發出HTTP請求時,系統可能拋出兩種異常,分別是ClientProtocolException和IOException。第一種異常的發生一般是協議錯誤致使,如在構造HttpGet對象時傳入的協議不對(例如不當心將"http"寫成"htp"),或者服務器端返回的內容不符合HTTP協議要求等;第二種異常通常是因爲網絡緣由引發的異常,如HTTP服務器未啓動等。
從實際應用的角度看,HTTP協議由兩大部分組成:HTTP請求和HTTP響應。那麼HttpClient程序包是如何實現HTTP客戶端應用的呢?實現過程當中須要注意哪些問題呢?
HTTP 1.1由如下幾種請求組成:GET, HEAD, POST, PUT, DELETE, TRACE and OPTIONS, 程序包中分別用HttpGet, HttpHead, HttpPost, HttpPut, HttpDelete, HttpTrace, and HttpOptions 這幾個類建立請求。全部的這些類均實現了HttpUriRequest接口,故能夠做爲execute的執行參數使用。
全部請求中最經常使用的是GET與POST兩種請求,與建立GET請求的方法相同,能夠用以下方法建立一個POST請求:
HttpUriRequest request = new HttpPost(
"http://localhost/index.html");
HttpUriRequest request = new HttpPost(
"http://localhost/index.html");
HTTP請求格式 告訴咱們,有兩個位置或者說兩種方式能夠爲request提供參數:request-line方式與request-body方式。
request-line方式是指在請求行上經過URI直接提供參數。
(1)
咱們能夠在生成request對象時提供帶參數的URI,如:
HttpUriRequest request = new HttpGet(
"http://localhost/index.html?param1=value1¶m2=value2");
HttpUriRequest request = new HttpGet(
"http://localhost/index.html?param1=value1¶m2=value2");
(2)
另外,HttpClient程序包爲咱們提供了URIUtils工具類,能夠經過它生成帶參數的URI,如:
URI uri = URIUtils.createURI("http", "localhost", -1, "/index.html",
"param1=value1¶m2=value2", null);
HttpUriRequest request = new HttpGet(uri);
System.out.println(request.getURI());
URI uri = URIUtils.createURI("http", "localhost", -1, "/index.html",
"param1=value1¶m2=value2", null);
HttpUriRequest request = new HttpGet(uri);
System.out.println(request.getURI());
上例的打印結果以下:
http://localhost/index.html?param1=value1¶m2=value2
(3)
須要注意的是,若是參數中含有中文,需將參數進行URLEncoding處理,如:
String param = "param1=" + URLEncoder.encode("中國", "UTF-8") + "¶m2=value2";
URI uri = URIUtils.createURI("http", "localhost", 8080,
"/sshsky/index.html", param, null);
System.out.println(uri);
String param = "param1=" + URLEncoder.encode("中國", "UTF-8") + "¶m2=value2";
URI uri = URIUtils.createURI("http", "localhost", 8080,
"/sshsky/index.html", param, null);
System.out.println(uri);
上例的打印結果以下:
http://localhost/index.html?param1=中國¶m2=value2
(4)
對於參數的URLEncoding處理,HttpClient程序包爲咱們準備了另外一個工具類:URLEncodedUtils。經過它,咱們能夠直觀的(可是比較複雜)生成URI,如:
List params = new ArrayList();
params.add(new BasicNameValuePair("param1", "中國"));
params.add(new BasicNameValuePair("param2", "value2"));
String param = URLEncodedUtils.format(params, "UTF-8");
URI uri = URIUtils.createURI("http", "localhost", 8080,
"/sshsky/index.html", param, null);
System.out.println(uri);
List params = new ArrayList();
params.add(new BasicNameValuePair("param1", "中國"));
params.add(new BasicNameValuePair("param2", "value2"));
String param = URLEncodedUtils.format(params, "UTF-8");
URI uri = URIUtils.createURI("http", "localhost", 8080,
"/sshsky/index.html", param, null);
System.out.println(uri);
上例的打印結果以下:
http://localhost/index.html?param1=中國¶m2=value2
與request-line方式不一樣,request-body方式是在request-body中提供參數,此方式只能用於POST請求。在HttpClient程序包中有兩個類能夠完成此項工做,它們分別是UrlEncodedFormEntity類與MultipartEntity類。這兩個類均實現了HttpEntity接口。
(1)
使用最多的是UrlEncodedFormEntity類。經過該類建立的對象能夠模擬傳統的HTML表單傳送POST請求中的參數。以下面的表單:
<</SPAN>form action="http://localhost/index.html" method="POST">
<</SPAN>input type="text" name="param1" value="中國"/>
<</SPAN>input type="text" name="param2" value="value2"/>
<</SPAN>inupt type="submit" value="submit"/>
</</SPAN>form>
<</SPAN>form action="http://localhost/index.html" method="POST">
<</SPAN>input type="text" name="param1" value="中國"/>
<</SPAN>input type="text" name="param2" value="value2"/>
<</SPAN>inupt type="submit" value="submit"/>
</</SPAN>form>
咱們能夠用下面的代碼實現:
List formParams = new ArrayList();
formParams.add(new BasicNameValuePair("param1", "中國"));
formParams.add(new BasicNameValuePair("param2", "value2"));
HttpEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8");
HttpPost request = new HttpPost(「http://localhost/index.html」);
request.setEntity(entity);
List formParams = new ArrayList();
formParams.add(new BasicNameValuePair("param1", "中國"));
formParams.add(new BasicNameValuePair("param2", "value2"));
HttpEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8");
HttpPost request = new HttpPost(「http://localhost/index.html」);
request.setEntity(entity);
固然,若是想查看HTTP數據格式,能夠經過HttpEntity對象的各類方法取得。如:
List formParams = new ArrayList();
formParams.add(new BasicNameValuePair("param1", "中國"));
formParams.add(new BasicNameValuePair("param2", "value2"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8");
System.out.println(entity.getContentType());
System.out.println(entity.getContentLength());
System.out.println(EntityUtils.getContentCharSet(entity));
System.out.println(EntityUtils.toString(entity));
List formParams = new ArrayList();
formParams.add(new BasicNameValuePair("param1", "中國"));
formParams.add(new BasicNameValuePair("param2", "value2"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8");
System.out.println(entity.getContentType());
System.out.println(entity.getContentLength());
System.out.println(EntityUtils.getContentCharSet(entity));
System.out.println(EntityUtils.toString(entity));
上例的打印結果以下:
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
39
UTF-8
param1=中國¶m2=value2
(2)
除了傳統的application/x-www-form-urlencoded表單,咱們另外一個常常用到的是上傳文件用的表單,這種表單的類型爲multipart/form-data。在HttpClient程序擴展包(HttpMime)中專門有一個類與之對應,那就是MultipartEntity類。此類一樣實現了HttpEntity接口。以下面的表單:
<</SPAN>form action="http://localhost/index.html" method="POST"
enctype="multipart/form-data">
<</SPAN>input type="text" name="param1" value="中國"/>
<</SPAN>input type="text" name="param2" value="value2"/>
<</SPAN>input type="file" name="param3"/>
<</SPAN>inupt type="submit" value="submit"/>
</</SPAN>form>
<</SPAN>form action="http://localhost/index.html" method="POST"
enctype="multipart/form-data">
<</SPAN>input type="text" name="param1" value="中國"/>
<</SPAN>input type="text" name="param2" value="value2"/>
<</SPAN>input type="file" name="param3"/>
<</SPAN>inupt type="submit" value="submit"/>
</</SPAN>form>
咱們能夠用下面的代碼實現:
MultipartEntity entity = new MultipartEntity();
entity.addPart("param1", new StringBody("中國", Charset.forName("UTF-8")));
entity.addPart("param2", new StringBody("value2", Charset.forName("UTF-8")));
entity.addPart("param3", new FileBody(new File("C:\\1.txt")));
HttpPost request = new HttpPost(「http://localhost/index.html」);
request.setEntity(entity);
MultipartEntity entity = new MultipartEntity();
entity.addPart("param1", new StringBody("中國", Charset.forName("UTF-8")));
entity.addPart("param2", new StringBody("value2", Charset.forName("UTF-8")));
entity.addPart("param3", new FileBody(new File("C:\\1.txt")));
HttpPost request = new HttpPost(「http://localhost/index.html」);
request.setEntity(entity);
HttpClient程序包對於HTTP響應的處理較之HTTP請求來講是簡單多了,其過程一樣使用了HttpEntity接口。咱們能夠從HttpEntity對象中取出數據流(InputStream),該數據流就是服務器返回的響應數據。須要注意的是,HttpClient程序包不負責解析數據流中的內容。如:
HttpUriRequest request = ...;
HttpResponse response = httpClient.execute(request);
// 從response中取出HttpEntity對象
HttpEntity entity = response.getEntity();
// 查看entity的各類指標
System.out.println(entity.getContentType());
System.out.println(entity.getContentLength());
System.out.println(EntityUtils.getContentCharSet(entity));
// 取出服務器返回的數據流
InputStream stream = entity.getContent();
// 以任意方式操做數據流stream
// 調用方式 略
HttpUriRequest request = ...;
HttpResponse response = httpClient.execute(request);
// 從response中取出HttpEntity對象
HttpEntity entity = response.getEntity();
// 查看entity的各類指標
System.out.println(entity.getContentType());
System.out.println(entity.getContentLength());
System.out.println(EntityUtils.getContentCharSet(entity));
// 取出服務器返回的數據流
InputStream stream = entity.getContent();
// 以任意方式操做數據流stream
// 調用方式 略
本文說明的是HttpClient 4.0.1 ,該程序包(包括依賴的程序包)由如下幾個JAR包組成: commons-logging-1.1.1.jarcommons-codec-1.4.jarhttpcore-4.0.1.jarhttpclient-4.0.1.jarapache-mime4j-0.6.jarhttpmime-4.0.1.jar