需要jar包
commons-logging-1.1.1.jar
httpclient-4.1.2.jar
httpcore-4.1.2.jar
package Demo05;
//记住导包的方法
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
//网上下载第二种方式 http协议下的下载
//第二种方法的前提是需要导入jar包
public class Test02 {
public static void main(String[] args) {
HttpClient client=new DefaultHttpClient();
HttpGet get=new HttpGet("http://photocdn.sohu.com/20150610/mp18368185_1433925691994_2.jpg");//下载文件的网址
InputStream is=null;
FileOutputStream fos=null;
try {
HttpResponse response=client.execute(get);
if(response.getStatusLine().getStatusCode()==200){
HttpEntity entity=response.getEntity();
is=entity.getContent();//关键的一步 算是有个转换的过程
fos=new FileOutputStream("c.jpg");
byte[] cub=new byte[1024];
int num=0;
while((num=is.read(cub))!=-1){
fos.write(cub, 0, num);
fos.flush();
}
System.out.println("下载完毕");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(is!=null){
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
网络编程,http协议下载文件的第二种方式
最新推荐文章于 2019-03-24 21:06:10 发布