標籤:
http://hc.apache.org/httpclient-3.x/tutorial.html
The general process for using HttpClient consists of a number of steps:
Create an instance of HttpClient.
Create an instance of one of the methods (GetMethod in this case). The URL to connect to is passed in to the the method constructor.
Tell HttpClient to execute the method.
Read the response.
Release the connection.
Deal with the response.
httpClient可以和server自動的進行驗證,但是開發人員需要提供給httpClient驗證需要的credentials,這些資訊被儲存在HttpState中,httpState的instance可以通過setCredentials(AuthScope authscope, Credentials cred) and getCredentials(AuthScope authscope) 來擷取和設定.在httpClient中的自動驗證只可以通過httpMethod來取消,只限於這這method.setDoAuthentication(boolean doAuthentication)
當沒有明確指定需要驗證的時候,host會把default的驗證資訊發出去.所以當訪問不可信的網站的時候,我們並不希望把credentials的資訊發出去,所以我們在httpClient設定發送credentials的範圍.以下設定的是對於任何site都發生credentials的資訊,這個是不推薦的.
// To be avoided unless in debug mode
Credentials defaultcreds = new UsernamePasswordCredentials("username", "password");
client.getState().setCredentials(AuthScope.ANY, defaultcreds);
使用代理時的驗證和server的驗證是一樣的,但是有單獨的設定和擷取驗證的方法:
etProxyCredentials(AuthScope authscope, Credentials cred) and getProxyCredentials(AuthScope authscope).
httpClient支援的authentication scheme: basic, Digest, NTLM
1.basic的scheme是最基本的,也是相容性最好的,但也是最不安全的,它的問題是它在傳輸使用者名稱和密碼的時候,沒有經過加密.使用這種模式的時候,必須顯示的提供或使用預設的UsernamePasswordCredentials
2.Digest很安全,它是通過client來對server發回的一個nonce的一個值進行加密,然後發回去,不會把密碼發送.它的問題是,可能不是很好的被http支援.它也需要顯示的提供或使用預設的UsernamePasswordCredentials
3.NTLM是由微軟研發的一套驗證的方法,它在windows NT4中是固定的.NTLM驗證需要一個NTCredentials對於需要的domain name,或者一個default的credentials.使用NTLM與使用其他倆個驗證方法有一些不同:
a.你需要提供 NTCredentials而不是UsernamePasswordCredentials.
b.在NTLM驗證中的realm是你連的那台電腦的domain name,所以,當一台電腦的有多個domain name的時候,就會有麻煩.自有httpClient串連的那個domain name才會尋找對應的credentials.((as specified by the HostConfiguration). It is generally advised that while initially testing NTLM authentication, you pass the realm in as null which is used as the default.
c.NTLM是一個串連而不是一個request,所以在每次開一個新的串連的時候都需要進行驗證.所以,在http 1.0中不支援NTLM
我們可以提供給httpClient多種驗證的scheme,但是在實際進行驗證的時候,httpClient會選擇其中的一個.預設三種scheme是有一定的優先順序的:NTLM,Digest,Basic
The default preference of the authentication schemes may be altered using the ‘http.auth.scheme-priority‘ parameter. The parameter value is expected to be a List of Strings containing names of authentication schemes in descending order of preference.
HttpClient client = new HttpClient();
List authPrefs = new ArrayList(2);
authPrefs.add(AuthPolicy.DIGEST);
authPrefs.add(AuthPolicy.BASIC);
// This will exclude the NTLM authentication scheme
client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
除了以上三種http自持的驗證方法,httpClient也支援customed的驗證方法,只要
1.Implement the AuthScheme interface.
2.Register the custom AuthScheme with AuthPolicy.registerAuthScheme().
3.Include the custom AuthScheme in the AuthPolicy.AUTH_SCHEME_PRIORITY preference (see the Alternate authentication section).
public class BasicAuthenticationExample {
46
47 /**
48 * Constructor for BasicAuthenticatonExample.
49 */
50 public BasicAuthenticationExample() {
51 super();
52 }
53
54 public static void main(String[] args) throws Exception {
55 HttpClient client = new HttpClient();
56
57 // pass our credentials to HttpClient, they will only be used for
58 // authenticating to servers with realm "realm" on the host
59 // "www.verisign.com", to authenticate against
60 // an arbitrary realm or host change the appropriate argument to null.
61 client.getState().setCredentials(
62 new AuthScope("www.verisign.com", 443, "realm"),
63 new UsernamePasswordCredentials("username", "password")
64 );
65
66 // create a GET method that reads a file over HTTPS, we‘re assuming
67 // that this file requires basic authentication using the realm above.
68 GetMethod get = new GetMethod("https://www.verisign.com/products/index.html");
69
70 // Tell the GET method to automatically handle authentication. The
71 // method will use any appropriate credentials to handle basic
72 // authentication requests. Setting this value to false will cause
73 // any request for authentication to return with a status of 401.
74 // It will then be up to the client to handle the authentication.
75 get.setDoAuthentication( true );
76
77 try {
78 // execute the GET
79 int status = client.executeMethod( get );
80
81 // print the status and response
82 System.out.println(status + "\n" + get.getResponseBodyAsString());
83
84 } finally {
85 // release any connection resources used by the method
86 get.releaseConnection();
87 }
88 }
89 }
httpClient的編碼問題主要涉及到三個方面:header,Body,還有url
headers必須是us-ascll編碼.由於cookie在頭裡,所以cookie也必須是使用us-ascll編碼.
body中的編碼可以是任意的編碼,預設是ISO-8859-1,它的編碼可以在Content-type中指定.
Content-Type: text/html; charset=UTF-8
在這種情況下,httpClient可以放心的使用UTF-8編碼來把body轉換成string.你可以設定requestheader中的content-type,通過 addRequestHeader
也可以獲得response body的編碼方式,使用getResponseCharSet方法.如果確定返回的結果是一個string,你可以使用 getResponseBodyAsString方法,他會自動的使用content-type中指定的編碼集來解出字元,如果沒有content-type的header,就會使用預設的編碼ISO-8859-1
需要注意的是一個檔案,例如xml/html允許指定檔案的編碼,這種情況下,你就需要使用合適的編碼來對檔案進行解析,可能檔案中指定的編碼和response的header中不一樣.
url:url的協議明確規定了url使用us-ascll編碼,而且是以位元組的方式來定義的.16進位的字元不在us-ascll中,所以有的十六進位是有一些控制符作為首碼的,在這些範圍的字元一定要進行編碼.無法使用us-ascll編碼的字元無法出現在url中.
Despite this, some servers do support varying means of encoding double byte characters in URLs, the most common technique seems to be to use UTF-8 encoding and encode each octet separately even if a pair of octets represents one character. This however, is not specified by the standard and is highly prone to error, so it is recommended that URLs be restricted to the 8-bit ASCII range.
關於redirect: 還是看原文吧: http://hc.apache.org/httpclient-3.x/redirects.html 感覺沒什麼重點.主要是一些重新導向的status 3XX,看一下每個status表示的含義.
使用httpClient會遇到的異常主要包括倆種異常:transport exception,還有protocol exception.不是所有的異常都會在httpClient中被拋出,有些異常在內部就會被處理掉.
transport exception是由輸入輸出的失敗造成的,這些錯誤一般是由於不可靠的網路傳輸,或者在一次操作中產生了逾時,比如cookie的到期.一般來說,transport的異常不是致命的,可以進行重試.但是如果一個操作不是等冪的,就需要注意了.
一般transport的exception是由ioException或者它的子類例如SocketException,InterruptedIOException來代表.除了這些標準的輸入輸出的異常,httpClient還自訂了一些transport exception的異常.
java.io.IOException
+- org.apache.commons.httpclient.NoHttpResponseException
NoHttpResponceException:這個異常是由於,當用戶端向伺服器扔出過多的異常,伺服器可能會承擔不住,所以server會接受來的請求,但是不會做出response.這個時候就會拋出這個異常.然後處理的時候,可以降低發出請求的速度,然後進行重試.
java.io.IOException
+- java.io.InterruptedIOException
+- org.apache.commons.httpclient.ConnectTimeoutException
org.apache.commons.httpclient.ConnectTimeoutException:這個異常表示httpClient無法和serve或者代理建立串連,在一定的時間內,所以照成了逾時.
java.io.IOException
+- java.io.InterruptedIOException
+- org.apache.commons.httpclient.ConnectTimeoutException
+- org.apache.commons.httpclient.ConnectionPoolTimeoutException
這個異常只有在使用multithreaded connection manager的時候才會發生,它表示一個connection management在一定的時間內無法在串連池中獲得一個閒置串連.
java.io.IOException
+- org.apache.commons.httpclient.HttpException
+- org.apache.commons.httpclient.HttpRecoverableException
這個異常現在已經被廢棄了,在標準的httpClient的類和方法中不會再被拋出.
Protocol exception.通常是由server(target server或者proxy server)和client的不匹配照成的,所以出現這個異常的時候,需要對發生的請求的一些資訊進行修改.
java.io.IOException
+- org.apache.commons.httpclient.HttpException
這個異常表示了這種邏輯上的不匹配造成的錯誤.一般需要對請求資訊進行修改.
java.io.IOException
+- org.apache.commons.httpclient.HttpException
+- org.apache.commons.httpclient.ProtocolException
ProtocolException signals a violation of the HTTP specification. It is important to note that HTTP proxies and HTTP servers can have different level of HTTP specification compliance. It may be possible to recover from some HTTP protocol exceptions by configuring HttpClient to be more lenient about non-fatal protocol violations.
還有其他一些在內部就被處理了的異常,包括在驗證操作出現的錯誤:驗證的設定檔找不到,驗證錯誤,驗證被拒絕,cookie錯誤,自動處理redirect的時候出現的非法的redirect,uri不對等等異常.
http是無狀態的,所以需要注意http請求的等冪性.
有少數的異常,httpClient在捕捉到後,會嘗試進行恢複.httpClient不會對protocol的exception.當發生transport的異常的時候,httpClient會自動的重複up to 5次的操作,來嘗試恢複.或者是你的request打到server後,server沒有返回status,也就是說server可能把這個request丟掉了.如果在出現上述情況的時候,可能一些應用或者server的狀態會發生改變,則最好我們自己去定製內部處理這些異常的方法.
如果想要定製處理內部異常的方法,就需要實現HttpMethodRetryHandler,然後在httpMethod中setParameter,指定使用哪個RETRY_HANDLER;
HttpClient client = new HttpClient();
HttpMethodRetryHandler myretryhandler = new HttpMethodRetryHandler() {
public boolean retryMethod(
final HttpMethod method,
final IOException exception,
int executionCount) {
if (executionCount >= 5) {
// Do not retry if over max retry count
return false;
}
if (exception instanceof NoHttpResponseException) {
// Retry if the server dropped connection on us
return true;
}
if (!method.isRequestSent()) {
// Retry if the request has not been sent fully or
// if it‘s OK to retry methods that have been sent
return true;
}
// otherwise do not retry
return false;
}
};
GetMethod httpget = new GetMethod("http://www.whatever.com/");
httpget.getParams().
setParameter(HttpMethodParams.RETRY_HANDLER, myretryhandler);
try {
client.executeMethod(httpget);
System.out.println(httpget.getStatusLine().toString());
} finally {
httpget.releaseConnection();
}
關於httpClient的log,它使用的是common log,所我們可以在底層使用其他的log實現. HttpClient performs two different kinds of logging: the standard context logging used within each class, and wire logging.
httpClient-3.1學習筆記