介绍
使用springboot框架,使用restTemplate去发送http请求下载文件,带头信息和json报文内容。
示例
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
/**
* 带头信息、body的文件下载
*
* @author jianghao
*/
@RestController
@RequestMapping("/file")
public class FileOperationController {
private final RestTemplateBuilder restTemplate;
public FileOperationController(RestTemplateBuilder restTemplate) {
this.restTemplate = restTemplate;
}
/**
* 下载文件
*/
@GetMapping("/download")
public void downloadFile(){
try {
// JSON数据
String data = "{\"infno\":\"9102\",\"msgid\":\"P4301020103820210510111608244\",\"insuplc_admdvs\":\"431102\",\"mdtrtarea_admvs\":\"431102\",\"recer_sys_code\":\"DHCC\",\"cainfo\":\"\",\"dev_no\":\"\",\"dev_safe_info\":\"\",\"signtype\":\"SM3\",\"infver\":\"V1.0\",\"opter_type\":\"1\",\"opter\":\"1\",\"opter_name\":\"demo\",\"inf_time\":\"2021-05-10 11:16:08\",\"fixmedins_code\":\"H43112900275\",\"fixmedins_name\":\"江华瑶族自治县第一人民医院\",\"sign_no\":\"193\",\"input\":{\"fsDownloadIn\":{\"file_qury_no\":\"M00/00/01/CloAOmCc4KCANS8tAAAB201aOdE6910323\",\"filename\":\"202105139172706019957799951.txt.zip\",\"fixmedins_code\":\"H43112900275\"}}}";
restTemplate.build().execute(
"http://39g35124f0.wicp.vip/power-csb/powercsb/9102",
HttpMethod.POST,
clientHttpRequest -> {
//加入头信息
HttpHeaders headers = clientHttpRequest.getHeaders();
headers.add("Content-Type","text/plain");
headers.add("User-Agent","PostmanRuntime/7.28.0");
headers.add("Accept","*/*");
headers.add("Host","39g35124f0.wicp.vip");
headers.add("Accept-Encoding","gzip, deflate, br");
headers.add("Connection","keep-alive");
headers.add("Content-Length","754");
headers.add("Cookie","XSRF-TOKEN=b5bc59d7-da08-48ac-b50c-c44552f88c3f");
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_OCTET_STREAM));
// 加入Body的JSON内容
clientHttpRequest.getBody().write(data.getBytes(StandardCharsets.UTF_8));
},
clientHttpResponse -> {
// 下载文件存放的地方
File file =new File("G:\\202105139172706019957799951.txt.zip");
StreamUtils.copy(clientHttpResponse.getBody(), new FileOutputStream(file, true));
return file;
});
}catch (Exception e){
e.printStackTrace();
}
}
}