Java下载文件(特殊字符编码处理)

当你在这个问题上花费了数小时而解决不了,你才会知道这篇文章对你的帮助

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StreamUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;

public class Test {
    @Autowired
    RestTemplate restTemplate;

    public void test(HttpServletResponse response) {
        String serverPrefix = "http://aa.com:8080";
        String filePath = "/testo1/test2/測武特殊字付@#&$%^~+[】・副本一副本・pom";
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Auth");
        URI uri = UriComponentsBuilder
                .fromHttpUrl(serverPrefix)
                .pathSegment(filePath.split("/"))
                .build()
                .encode()
                .toUri();
        ResponseEntity<Resource> responseEntity = restTemplate
                .exchange(uri, HttpMethod.GET, new HttpEntity<>(headers), Resource.class);
        if (responseEntity.getStatusCode().is2xxSuccessful() && responseEntity.hasBody()) {
            try (InputStream input = responseEntity.getBody().getInputStream();
                 OutputStream output = response.getOutputStream()) {
                StreamUtils.copy(input, output);
                response.setContentLengthLong(responseEntity.getBody().contentLength());
            } catch (IOException e) {
                throw new RuntimeException("流传输异常", e);
            }
        } else {
            throw new RuntimeException("请求失败:" + responseEntity.getStatusCode());
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值