restTemplate发送post请求时修改请求头和上传文件

1.restTemplate发送post请求时修改请求头

@PostMapping("/buyWater")
    public ObjectResult buyWater(@RequestBody Food food) throws Exception {
        String url = "https://192.168.98.172/ConvertService.ashx";
        String downUrl = "http://192.168.98.172/cache/files/1548230402889_635/output.docx/output.docx?md5=DzQ_apBwhgxzjAmlGsSi-w==&expires=1548231320&disposition=attachment&ooname=output.docx";
        ConvertObject convertObject = new ConvertObject(false,"docx","1548230402889","txt","wang_min",downUrl);
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        String json = JsonUtils.toJson(convertObject);
        HttpEntity formEntity = new HttpEntity(json, headers);
        Object result = restTemplate.postForObject(url, formEntity, Object.class);
        return ObjectResult.success(result.toString());
    }

2.上传文件

@GetMapping("/uploadPhoto")
    public ObjectResult uploadPhoto() throws Exception {
        File file = new File("F:/pic/test.jpg");
        FileSystemResource resource = new FileSystemResource(file);
        String url = "http://localhost:8080/user/uploadPhoto";
        MultiValueMap param = new LinkedMultiValueMap<>();
        param.add("file", resource);
        param.add("name", "我的头像");
        param.add("size", "12M");
        restTemplate.postForObject(url, param, Object.class);
        return ObjectResult.success("success");
    }

你可能感兴趣的:(实用小知识)