Posted in Java/Android onAugust 14, 2022
使用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、检查文件完整性,没啥问题:)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。
Java使用HttpClient实现文件下载
- Author -
杨某不才- Original Sources -
声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@