Java使用HttpClient实现文件下载

使用HttpClient实现文件下载,供大家参考,具体内容如下

服务端:

1、服务端是一个SpringBoot服务,写了一个接口用于客户端请求文件,客户端携带参数(文件名fileName)使用Get方式请求;

2、服务端获取到文件名后将与本地仓库地址E:/downloadRepository/组成绝对路径,获取文件转换成流,最后利用OutputStream对象将缓冲区的数据送到客户端;

3、缓冲区大小也可设置为一个定值(如:1024*1024),然后再循环写入输出流对象;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
public class RequestController {
    @RequestMapping(path = "/download", method = RequestMethod.GET)
    public void downLoad(HttpServletResponse response, String fileName){
        File file = new File("E:/downloadRepository/" + fileName);
        try{
            InputStream inputStream = new BufferedInputStream (new FileInputStream(file));
            //创建缓冲区
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            inputStream.close();
            OutputStream outputStream = new BufferedOutputStream(response
                    .getOutputStream());
            outputStream.write(buffer);
            outputStream.flush();
            outputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

原文件:

1、原文件所在地址;

2、原文件内容;

客户端:

1、请求参数为一个文件的文件名,这里我们通过URIBuilder对象的addParameter()方法来进行设置请求参数;

2、在状态码等于200时,将请求来的文件利用FileUtils工具类将字符串转换成文件,并且该方法可以设置保存路径;

import org.apache.commons.io.FileUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.*;

public class RequestFileService {

    public void httpRequest(String fileName) {
            // 请求地址
            String url = "http://localhost:8080/download";
            // 下载文件保存路径
            String savePath = "E:/demo/" + fileName;
            CloseableHttpClient httpclient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            try {
                // 使用URIBuilder对象用于设置请求参数
                URIBuilder urlBuilder = new URIBuilder(url);
                urlBuilder.addParameter("fileName", fileName);
                HttpGet httpGet = new HttpGet(urlBuilder.build());
                // 执行请求
                response = httpclient.execute(httpGet);
                if (response.getStatusLine().getStatusCode() == 200) {
                    String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                    // 将请求内容转换成文件并保存
                    FileUtils.writeStringToFile(new File(savePath), content, "UTF-8");
                }
            } catch (Exception e) {
                e.getStackTrace();
            }finally {
                try {
                    response.close();
                    httpclient.close();
                }catch (IOException e){
                    e.getStackTrace();
                }
            }
    }

    public static void main(String[] args) {
        RequestFileService requestFileService = new RequestFileService();
        //参数为请求文件名
        requestFileService.httpRequest("205老面馆.txt");
    }
}

下载结果:

1、按照代码所设定的路径,应该存在E:/demo/目录下;

2、检查文件完整性,没啥问题:)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • 使用HttpClient实现文件的上传下载方法

    1 HTTP HTTP 协议可能是现在 Internet 上使用得最多.最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源. 虽然在 JDK 的 java.net 包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活.HttpClient 用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议. 一般的情况下我们都是使用Chrome或者

  • Android开发之HttpClient异步请求数据的方法详解【附demo源码下载】

    本文实例讲述了Android开发之HttpClient异步请求数据的方法.分享给大家供大家参考,具体如下: 前面一篇Android开发笔记之:AsyncTask的应用较为详细的讲述了Asynctask的原理与应用,这里来结合使用一下HttpClient与Asynctask~ 代码编写如下: 服务器代码我就不写出来了,就是一个用户名和密码~ 1.写一个类HttpClientUtil,来实现HttpClient对象的创建并且返回HttpResponse对象 public class HttpClie

  • android通过okhttpClient下载网页内容的实例代码

    有时候我们需要通过自己的缓存机制来缓存网页内容,当没有网的时候显示本地的缓存,当有网的时候取最新的继续缓存到本地. 主要机制: 通过AsyncTask异步AsyncTask请求,将得到的response.body()缓存起来. 主要代码如下: //通过OkHttpClient加载html的方式先判断网页是否能走通 class WebViewStatusRequester extends AsyncTask<String, String, Integer> { String url; @Over

  • Java使用HttpClient实现文件下载

    使用HttpClient实现文件下载,供大家参考,具体内容如下 服务端: 1.服务端是一个SpringBoot服务,写了一个接口用于客户端请求文件,客户端携带参数(文件名fileName)使用Get方式请求: 2.服务端获取到文件名后将与本地仓库地址E:/downloadRepository/组成绝对路径,获取文件转换成流,最后利用OutputStream对象将缓冲区的数据送到客户端: 3.缓冲区大小也可设置为一个定值(如:1024*1024),然后再循环写入输出流对象: import org.

  • Java利用httpclient通过get、post方式调用https接口的方法

    通过httpclient的get post方式调用http很常见.一般都是 HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(http://127.0.0.1/login); 但是如果要调用https这个方式就不行了.就要修改DefaultHttpClient <dependency> <groupId>org.apache.httpcomponents</groupId>

  • 使用java的HttpClient实现多线程并发

    说明:以下的代码基于httpclient4.5.2实现. 我们要使用java的HttpClient实现get请求抓取网页是一件比较容易实现的工作: public static String get(String url) { CloseableHttpResponseresponse = null; BufferedReader in = null; String result = ""; try { CloseableHttpClienthttpclient = HttpClient

  • java 中HttpClient传输xml字符串实例详解

    java 中HttpClient传输xml字符串实例详解 介绍:我现在有一个对象page,需要将page对象转换为xml格式并以binary方式传输到服务端 其中涉及到的技术点有: 1.对象转xml流 2.输出流转输入流 3.httpClient发送二进制流数据 POM文件依赖配置 <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifact

  • JAVA利用HttpClient进行POST请求(HTTPS)实例

    最近,需要对客户的接口做一个包装,然后供自己公司别的系统调用,客户接口是用HTTP URL实现的,我想用HttpClient包进行请求,同时由于请求的URL是HTTPS的,为了避免需要证书,所以用一个类继承DefaultHttpClient类,忽略校验过程. 1.写一个SSLClient类,继承至HttpClient package com.pcmall.service.sale.miaomore.impl; import java.security.cert.CertificateExcept

  • java实现HttpClient异步请求资源的方法

    本文实例讲述了java实现HttpClient异步请求资源的方法.分享给大家供大家参考.具体实现方法如下: package demo; import java.util.concurrent.CountDownLatch; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.nio.client.DefaultHttpAsyn

  • java发送HttpClient请求及接收请求结果过程的简单实例

    一. 1.写一个HttpRequestUtils工具类,包括post请求和get请求 package com.brainlong.framework.util.httpclient; import net.sf.json.JSONObject; import org.apache.commons.httpclient.HttpStatus; import org.apache.http.HttpResponse; import org.apache.http.client.methods.Htt

  • JAVA利用HttpClient进行HTTPS接口调用的方法

    本文介绍了JAVA利用HttpClient进行HTTPS接口调用的方法,分享给大家,具体如下: 1.为了避免需要证书,所以用一个类继承DefaultHttpClient类,忽略校验过程. import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManage

  • java web response提供文件下载功能的实例讲解

    webapp项目的结构如下图: download.html文件的内容如下: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h1>资源下载:</h1> <p> 单纯地使用a标签时,只有浏览器不能解析的文

  • Java后台Controller实现文件下载操作

    代码 参数: 1.filePath:文件的绝对路径(d:\download\a.xlsx) 2.fileName(a.xlsx) 3.编码格式(GBK) 4.response.request不介绍了,从控制器传入的http对象 代码片. //控制器 @RequestMapping(UrlConstants.BLACKLIST_TESTDOWNLOAD) public void downLoad(String filePath, HttpServletResponse response, Http

随机推荐