??? client.executeMethod(get);
??? System.out.println(get.getResponseBodyAsString());
現在假設你需要使用基本的驗證機制來訪問一個頁面。在這種情況下,你需要使用HTTP Client類UsernamePasswordCredentials。下面是實現這一功能的代碼:
??? UsernamePasswordCredentials upc =
??????????? new UsernamePasswordCredentials("foo", "bar");
??? client.getState().setCredentials(null, null, upc);
??? get.setDoAuthentication(true);
在下面的代碼中,我們為get方法添加一個超時規范以防頁面的裝載時間過長。
client.setConnectionTimeout(60000);
從示例代碼中我們已經看到了,使用HTTP Client的屬性相當簡單。如果你的應用程序需要HTTP訪問,那么就不妨試一下HTTP Client。它比Java API中的Web感知類具有更多的特性,而且它的用法簡單。自己看一下吧,看它是否能滿足你的要求。
import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.methods.GetMethod;
public class HttpClientTip {
??? public static void main(String args[]) {
??????? try {
??????????? HttpClient client = new HttpClient();
??????????? GetMethod get = new GetMethod("
??????????? UsernamePasswordCredentials upc =
??????????????????? new UsernamePasswordCredentials("foo", "bar");
??????????? client.getState().setCredentials(null, null, upc);
??????????? get.setDoAuthentication(true);
??????????? client.setConnectionTimeout(60000);
??????????? client.executeMethod(get);
??????????? System.out.println(get.getResponseBodyAsString());
??????? }
??????? catch (IOException e) {
??????????? e.printStackTrace();
??????? }
??? }
?