posts - 23,comments - 66,trackbacks - 0
使用HTTP Client构建Web客户端
 

在你需要Web感知应用程序而Java API又不够用的时候,你可能需要看一下Jakarta Common的HTTP Client。使用HTTP Client很简单:首先创建一个HttpClient的实例,然后创建你需要使用的方法类型的一个实例,最后使用HttpClient的实例执行方法。


下面是设计Web页面并将其内容写到标准输出:

    HttpClient client = new HttpClient();
    GetMethod get = new GetMethod("http://www.google.com/");

    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("http://www.google.com/");

            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 阅读(1051) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: