如何用Java WebClient或RestTemplate实现指定cURL请求?
用Java WebClient/RestTemplate实现对应multipart/form-data PUT请求
原始请求参考
cURL示例
curl --location --request PUT '[url]' \ --header 'authorization: Bearer [token]' \ --form 'fileData="[json]"' \ --form 'file=@"/C:/path/file.json"'
原始HTTP请求
PUT [url] authorization: Bearer [token] User-Agent: PostmanRuntime/7.29.2 Accept: */* Cache-Control: no-cache Host: [host] Accept-Encoding: gzip, deflate, br Connection: keep-alive Content-Type: multipart/form-data; boundary=--------------------------821418838150769919184719 Content-Length: 121986 ----------------------------821418838150769919184719 Content-Disposition: form-data; name="fileData" [json] ----------------------------821418838150769919184719 Content-Disposition: form-data; name="file"; filename="file.json" <file.json> ----------------------------821418838150769919184719-- HTTP/1.1 200 OK Date: Sat, 27 Aug 2022 01:33:15 GMT Content-Type: application/json; charset=utf-8 Transfer-Encoding: chunked Connection: keep-alive Content-Encoding: br Vary: Accept-Encoding Request-Context: appId=cid-v1:55ff528b-00c0-4656-b479-7f1d61e8f50b Strict-Transport-Security: max-age=86400; includeSubDomains; preload [json response]
RestTemplate实现代码
直接构建multipart请求体,设置好授权头即可,框架会自动处理multipart的boundary:
import org.springframework.core.io.FileSystemResource; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import java.io.File; public class RestTemplateDemo { public static void main(String[] args) { // 替换成实际参数 String targetUrl = "[你的请求URL]"; String bearerToken = "[你的Bearer令牌]"; String fileDataJsonStr = "[你的JSON字符串内容]"; File targetFile = new File("C:/path/file.json"); // 构建请求头 HttpHeaders headers = new HttpHeaders(); headers.setBearerAuth(bearerToken); headers.setContentType(MediaType.MULTIPART_FORM_DATA); // 组装multipart表单数据 MultiValueMap<String, Object> formData = new LinkedMultiValueMap<>(); formData.add("fileData", fileDataJsonStr); formData.add("file", new FileSystemResource(targetFile)); // 发送PUT请求 RestTemplate restTemplate = new RestTemplate(); String responseBody = restTemplate.exchange( targetUrl, HttpMethod.PUT, new HttpEntity<>(formData, headers), String.class ).getBody(); System.out.println(responseBody); } }
WebClient实现代码
响应式方式的实现,同样处理multipart表单和授权头:
import org.springframework.core.io.FileSystemResource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.client.WebClient; import java.io.File; public class WebClientDemo { public static void main(String[] args) { // 替换成实际参数 String targetUrl = "[你的请求URL]"; String bearerToken = "[你的Bearer令牌]"; String fileDataJsonStr = "[你的JSON字符串内容]"; File targetFile = new File("C:/path/file.json"); WebClient webClient = WebClient.builder().build(); // 发送PUT请求,同步获取结果(异步场景可去掉block()) String responseBody = webClient.put() .uri(targetUrl) .header(HttpHeaders.AUTHORIZATION, "Bearer " + bearerToken) .contentType(MediaType.MULTIPART_FORM_DATA) .body(BodyInserters.fromMultipartData( "fileData", fileDataJsonStr, "file", new FileSystemResource(targetFile) )) .retrieve() .bodyToMono(String.class) .block(); System.out.println(responseBody); } }
注意事项
- 如果
fileData是Java对象,需要先转成JSON字符串,比如用Jackson的ObjectMapper:new ObjectMapper().writeValueAsString(yourObject) - 不要手动设置multipart的boundary,框架会自动生成并匹配请求体
- 确保本地文件路径正确,程序有读取文件的权限
内容的提问来源于stack exchange,提问作者Tom D
相关产品推荐
相关产品推荐

