网络数据的请求中,当然我指的是下载,有两个标胶常用的方法,一个是利用HttpURLCollection,这个之前也有提到过,还有一个就是 用HttpClient,两者的区别就是HttpURLCollection是Java JDK自带的,不需要其他jar包的支持,而HttpClient需要导入相应的jar包才可以使用!然后下面介绍怎么使用,都是一些常规使用方法!按照套路来即可。。。
package com.ctgu.httpclient;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class TestHttpClient {
public static void main(String[] args) {
//指定下载的地址
String path = "http://dl.bizhi.sogou.com/images/2013/09/03/365869.jpg?f=download";
//创建客户端
HttpClient client = new DefaultHttpClient();
//创建HttpGet请求
HttpGet get = new HttpGet(path);
try {
//执行请求 返回相应
HttpResponse httpResponse = client.execute(get);
if(httpResponse.getStatusLine().getStatusCode()==200){
System.out.println("请求正常");
HttpEntity entity = httpResponse.getEntity();
BufferedInputStream bis = new BufferedInputStream(entity.getContent());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("E:/img/6.jpg"));
byte[] b = new byte[1024];
int len = 0;
while((len = bis.read(b))!=-1){
bos.write(b, 0, len);
bos.flush();
}
bis.close();
bos.close();
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
需要说明的是,下载的是一张图片,大小也就几百KB,若要下载几个G的东西,推荐使用多线程断点续下,分开下载!下面看给出该网站下载的美女图片!