posts - 23,comments - 66,trackbacks - 0
          使用HTTP Client構(gòu)建Web客戶端
          ?

          在你需要Web感知應(yīng)用程序而Java API又不夠用的時候,你可能需要看一下Jakarta Common的HTTP Client。使用HTTP Client很簡單:首先創(chuàng)建一個HttpClient的實例,然后創(chuàng)建你需要使用的方法類型的一個實例,最后使用HttpClient的實例執(zhí)行方法。


          下面是設(shè)計Web頁面并將其內(nèi)容寫到標(biāo)準(zhǔn)輸出:

          ??? HttpClient client = new HttpClient();
          ??? GetMethod get = new GetMethod("

          ??? client.executeMethod(get);
          ??? System.out.println(get.getResponseBodyAsString());

          現(xiàn)在假設(shè)你需要使用基本的驗證機制來訪問一個頁面。在這種情況下,你需要使用HTTP Client類UsernamePasswordCredentials。下面是實現(xiàn)這一功能的代碼:

          ??? UsernamePasswordCredentials upc =
          ??????????? new UsernamePasswordCredentials("foo", "bar");

          ??? client.getState().setCredentials(null, null, upc);

          ??? get.setDoAuthentication(true);

          在下面的代碼中,我們?yōu)間et方法添加一個超時規(guī)范以防頁面的裝載時間過長。

          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();
          ??????? }
          ??? }

          ?

          posted on 2006-03-21 23:20 rd2pm 閱讀(1060) 評論(0)  編輯  收藏

          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導(dǎo)航:
           

          主站蜘蛛池模板: 临漳县| 浑源县| 庄河市| 武清区| 高雄县| 德庆县| 呼伦贝尔市| 达尔| 贡觉县| 同江市| 阜康市| 济源市| 门源| 武夷山市| 襄汾县| 卫辉市| 疏勒县| 沈阳市| 封丘县| 鲁山县| 武平县| 屏南县| 新安县| 合阳县| 贵港市| 荔浦县| 武隆县| 青州市| 闵行区| 金湖县| 贵南县| 南郑县| 宝丰县| 阳城县| 绥江县| 海门市| 赤壁市| 凉城县| 左贡县| 肃宁县| 繁昌县|