使用httpClient实现文件的下载功能

本文介绍了两种使用Java的HttpClient库下载服务器文件的方法。第一种方式详细展示了客户端和服务端的代码实现,第二种方式提到了所需的依赖jar包和类的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一种方式:

客户端用httpclient怎么下载服务器上的文件

客户端:

package it.shb.client;



import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;



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 ClientA {

     public void service(){

            String url = "http://127.0.0.1:8080/spring_springmvc_mybatis626/user/download.action";

            HttpClient client = new DefaultHttpClient();

            HttpGet get = new HttpGet(url);

            try {

               HttpResponse response = client.execute(get);

               InputStream is = response.getEntity().getContent();

                String localfile = "D://test.zip";

                File file = new File(localfile);

                if(!file.exists()){

                    file.createNewFile();

                }

                OutputStream os = new FileOutputStream(file);

                int read = 0;

                byte[] temp = new byte[1024*1024];

               while((read=is.read(temp))>0){

                    byte[] bytes = new byte[read];

                    //System提供了一个静态方法arraycopy(),我们可以使用它来实现数组之间的复制

                    System.arraycopy(temp, 0, bytes, 0, read);

                    os.write(bytes);

                }

                os.flush();

            } catch (ClientProtocolException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            } catch (IOException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }



        }

        public static void main(String[] args) {

            ClientA client = new ClientA();

            client.service();

        }

}

服务器端:

package it.shb.ssm.controller;

import it.shb.ssm.po.User;

import it.shb.ssm.service.impl.IUserService;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import javax.annotation.Resource;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;



@Controller

@RequestMapping("/user")

public class UserController {

  @Resource

  private IUserService userService;

 @RequestMapping("/download")

   public void download(HttpServletRequest request, HttpServletResponse response) throws IOException{

//      String filename = "下载.zip";

//      String rname = new String(filename.getBytes("iso-8859-1"),"utf-8");

    //  response.addHeader("Content-Disposition", "attachment;filename="+rname);

      response.addHeader("Content-Disposition", "attachment");

      response.setContentType("application/octet-stream");

      File file = new File("e://druid-1.0.13.zip");

      InputStream is = new BufferedInputStream(new FileInputStream(file));

      byte[] buffer = new byte[is.available()];

      is.read(buffer);

      is.close();

      OutputStream os = new BufferedOutputStream(response.getOutputStream());

      os.write(buffer);

      os.flush();

      os.close();

   }

}

第二种普通方式:

依赖jar包:

httpclient-4.0.jar

类的实现:

package it.shb.http;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;



/**

 * TODO 在此加入类描述

 * @author sunhongbing

 * @see it.shb.http.HttpPostArgumentTest1

 */

public class HttpPostArgumentTest1 {

     private String workPath = null;  

        private String downLoadUrl = null;  

        private CloseableHttpClient httpclient=  HttpClients.createDefault();  

        public void downLoad(String url, String dst) {  

            try {  

                HttpGet httpGet = new HttpGet(url);  

                HttpResponse httpResponse = httpclient.execute(httpGet);  

                HttpEntity entity = httpResponse.getEntity();  

                InputStream in = entity.getContent();  

                long length=entity.getContentLength();  

                if(length<=0){  

                    System.out.println("下载文件不存在!");  

                    return;  

                }  

                OutputStream out = new FileOutputStream(new File(dst));  

                saveTo(in, out);  

            } catch (IOException e) {  

                e.printStackTrace();  

            } catch (Exception e) {  

                e.printStackTrace();  

            }  

        }  

        public void saveTo(InputStream in, OutputStream out) throws Exception {  

            byte[] data = new byte[1024*1024];  

            int index =0;  

            while ((index=in.read(data) )!= -1) {  

                out.write(data,0,index);  

            }  

            in.close();  

            out.close();  

        }  

        public static void main(String args[]) {  

            HttpPostArgumentTest1 downLoad = new HttpPostArgumentTest1();  

            String url = "http://www.gjt.org/download/time/java/tar/javatar-2.5.tar.gz";  

            downLoad.downLoad(url, "E:\\javatar-2.5.tar.gz");  

        }  

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值