当你在这个问题上花费了数小时而解决不了,你才会知道这篇文章对你的帮助
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());
}
}
}