调用第三方下载接口,入参String id,Sring name,String class,参数不要拼接在url上,根据对端返回文件流(哟特殊字符,中文,空格)获取文件名,用Java的RestTemplate实现Controller层,帮我写并标注释,打印出入参日志
时间: 2023-04-11 15:01:15 浏览: 76
好的,这是一个技术问题,我可以回答。以下是Java的RestTemplate实现Controller层的代码,已经标注了注释,并打印了入参日志:
```java
@RestController
public class DownloadController {
@Autowired
private RestTemplate restTemplate;
@PostMapping("/download")
public ResponseEntity<byte[]> downloadFile(@RequestParam("id") String id,
@RequestParam("name") String name,
@RequestParam("class") String clazz) {
// 打印入参日志
System.out.println("id: " + id);
System.out.println("name: " + name);
System.out.println("class: " + clazz);
// 构造请求参数
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("id", id);
params.add("name", name);
params.add("class", clazz);
// 构造请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// 构造请求实体
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
// 发送POST请求
ResponseEntity<byte[]> responseEntity = restTemplate.exchange("http://example.com/download", HttpMethod.POST, requestEntity, byte[].class);
// 获取文件名
String filename = getFilenameFromResponseHeaders(responseEntity.getHeaders());
// 构造响应头
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
responseHeaders.setContentDisposition(ContentDisposition.builder("attachment").filename(filename).build());
// 返回响应实体
return new ResponseEntity<>(responseEntity.getBody(), responseHeaders, HttpStatus.OK);
}
private String getFilenameFromResponseHeaders(HttpHeaders headers) {
String contentDisposition = headers.getFirst(HttpHeaders.CONTENT_DISPOSITION);
String[] parts = contentDisposition.split(";");
for (String part : parts) {
part = part.trim();
if (part.startsWith("filename=")) {
return part.substring("filename=".length()).replaceAll("\"", "");
}
}
return null;
}
}
```