通过Apache的httpClient的get方式连接服务器下载图片到本地

来源:互联网 发布:python的idle是什么 编辑:程序博客网 时间:2024/06/17 01:49


要用Apache的包,必须添加这些包进去才可以。下载后解压后,放入程序的libs中。

http://download.csdn.net/detail/harryweasley/8784985


客户端程序:

package lgx.java.test;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;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;public class HttpClientGet {/** * @param args */public static void main(String[] args) {// 使用get方法连接服务器HttpGet httpGet = new HttpGet("http://192.168.1.48:8080/Test/test.jpg");HttpClient client = new DefaultHttpClient();FileOutputStream fos;try {// 客户端开始向指定的网址发送请求HttpResponse response = client.execute(httpGet);InputStream inputStream = response.getEntity().getContent();File file = new File("D:\\jj");if (!file.exists()) {file.mkdirs();}fos = new FileOutputStream("D:\\jj\\test.jpg");byte[] data = new byte[1024];int len = 0;while ((len = inputStream.read(data)) != -1) {fos.write(data, 0, len);}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} }}

服务端可以参考这篇文章http://blog.csdn.net/harryweasley/article/details/45840523

两个文章大同小异,不过一个是用的java接口实现,一个是Apache的接口实现


2 1