Java Http Client

为了准备LilyBookStore下一步的功能,访问豆瓣的API,今天熟悉了一下JDK和Commons HttpClient中和http相关的接口。Commons中的HttpClient现在已经从Commons中独立出来了,不过新的4.0版还没有stable的release,现在用的3.1还是打着Commons标记的。

JDK实例:

   public void exe(String urlAsString) throws IOException{ 
URL url = new URL(urlAsString);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
int size = conn.getHeaderFields().size();
for(int i=0; i< size; i++){
System.out.print(conn.getHeaderFieldKey(i)+"\t");
System.out.println(conn.getHeaderField(i));
}
System.out.println("Request Method: "+conn.getRequestMethod());
System.out.println("Response Code: "+conn.getResponseCode());
System.out.println("Response Message: " +conn.getResponseMessage());
System.out.println("Last Modified: " +conn.getLastModified());
System.out.println("ContentHandler: " +conn.getContent().getClass().getName());
InputStream in = (InputStream)conn.getContent();
FileOutputStream out = new FileOutputStream(new File("index.html"));
copyStream(in, out);

}


java.net.HttpURLConnection里主要注意的就是getContent方法,对于不同的请求返回不同的对象。普通网页返回的是sun.net.www.protocol.http.HttpURLConnection$HttpInputStream,而图片、音频文件返回的则是各自的handler。

Commons的HttpClient实例:

    public void exe(String urlAsString) throws IOException{ 
HttpClient client = new HttpClient();
HttpMethod http = new GetMethod(urlAsString);
http.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(1, false));
client.executeMethod(http);
System.out.println(http.getStatusCode());
System.out.println(http.getStatusText());
InputStream in = http.getResponseBodyAsStream();
FileOutputStream out = new FileOutputStream(new File("index2.html"));
copyStream(in, out);
http.releaseConnection();
}


Commons中除了getResponseBodyAsStream,还有getResponseBodyAsString,使用起来相对方便一些。

等开学以后到学校复杂的网络环境里试一下,再决定最后选择哪个。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值