【发布时间】:2021-09-07 12:40:35
【问题描述】:
我的服务器 (SpringBoot) 需要上传一个文件,我的客户端 (纯 Java) 需要在那里发送一个 byte[] 数组。
服务器端点如下所示:
@RequestMapping(value = "/", method = RequestMethod.POST, headers={"content-type=multipart/form-data"})
ResponseEntity<String> postBytes(@ApiParam(value = "Upload bytes.", example = "0") @RequestBody Bytes bytes) {
return ResponseEntity.ok(byteLinkService.postBytes(bytes.getBytes()));
}
客户端请求如下所示:
//byte[] bytes is my file to be uploaded
URL url = new URL(this.endpoint + "/bytelink/");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Authorization", "Bearer " + token);
con.setRequestProperty("Content-Type", "multipart/form-data");
con.setRequestProperty("Accept", "*");
con.setDoOutput(true);
String jsonInputString = "{\"bytes\": \"" + Arrays.toString(bytes) + "\"}";
try (OutputStream os = con.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
int status = con.getResponseCode();
System.out.println(status);
现在我得到了这个异常:
WARN o.s.w.s.m.s.DefaultHandlerExceptionResolver - Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported]
【问题讨论】:
-
您将输出流编码为utf-8,springboot不支持。
标签: java spring httpurlconnection