??? client.executeMethod(get);
??? System.out.println(get.getResponseBodyAsString());
現(xiàn)在假設(shè)你需要使用基本的驗(yàn)證機(jī)制來訪問一個(gè)頁面。在這種情況下,你需要使用HTTP Client類UsernamePasswordCredentials。下面是實(shí)現(xiàn)這一功能的代碼:
??? UsernamePasswordCredentials upc =
??????????? new UsernamePasswordCredentials("foo", "bar");
??? client.getState().setCredentials(null, null, upc);
??? get.setDoAuthentication(true);
在下面的代碼中,我們?yōu)間et方法添加一個(gè)超時(shí)規(guī)范以防頁面的裝載時(shí)間過長。
client.setConnectionTimeout(60000);
從示例代碼中我們已經(jīng)看到了,使用HTTP Client的屬性相當(dāng)簡單。如果你的應(yīng)用程序需要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();
??????? }
??? }
?