场景:使用RestTemplate调用文件下载请求失败。
String fileUrl = "http://xxxxxx?reqbody={????}";
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.exchange(fileUrl, HttpMethod.GET, entity, byte[].class);
问题原因
请求url中包含{},?等特殊字符
解决方法
1.使用URI类进行包装:
String fileUrl = "http://xxxxxxxxxxxxxx";
RestTemplate restTemplate = new RestTemplate();
URI uri = new URI(fileUrl);
String result = restTemplate.exchange(uri, HttpMethod.GET, entity, byte[].class);
2.使用Java的URLEncoder进行转换:
String fileUrl = "http://xxxxxxxxxxxxxx";
RestTemplate restTemplate = new RestTemplate();
String encodedUrl = URLEncoder.encode(fileUrl, "UTF-8");
String result = restTemplate.exchange(encodedUrl, HttpMethod.GET, entity, byte[].class);
补充:使用spring的org.springframework.web.util包下的UriComponentsBuilder对url进行包装
String fileUrl = "http://xxxxxxxxxxxxxx";
InputStream inputStream = null;
// 下载附件请求
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM));
HttpEntity<String> entity = new HttpEntity<>(headers);
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromHttpUrl(fileUrl);
URI uri = uriComponentsBuilder.build().encode().toUri();
ResponseEntity<byte[]> response = restTemplate.exchange(uri, HttpMethod.GET, entity, byte[].class);
byte[] fileData = response.getBody();
inputStream = new ByteArrayInputStream(fileData);