Java Http Client

论坛 期权论坛 脚本     
匿名技术用户   2020-12-28 03:04   11   0
为了准备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 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP