spring restTemplate 上传文件乱码问题

FormHttpMessageConverter 的

 
protected byte[] getAsciiBytes(String name) {
try {
return name.getBytes("US-ASCII");   //改为 UTF-8 就OK 了。
}
catch (UnsupportedEncodingException ex) {
// should not happen, US-ASCII is always supported
throw new IllegalStateException(ex);
}
}
	   HttpHeaders requestHeaders = new HttpHeaders();
	// Sending multipart/form-data
	   requestHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
	   
	   HttpHeaders headers = new HttpHeaders();
	   headers.setContentType(new MediaType("text" ,"plain",Charset.forName("UTF-8")));
	   HttpEntity<String> entity = new HttpEntity<String>("测试一下", headers);
	   MultiValueMap<String, Object> formData = new LinkedMultiValueMap<String, Object>();
	   
	   formData.add("caption",entity);
		
	   HttpHeaders headers1 = new HttpHeaders();
	   headers1.setContentType(new MediaType("application" ,"octet-stream",Charset.forName("UTF-8")));
//       xmlHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
       HttpEntity<FileSystemResource> fileEntity = new HttpEntity<FileSystemResource>(resource, headers1);
	   formData.add("file", fileEntity);
	   
	   
	   HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(formData, requestHeaders);

	   ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
 

猜你喜欢

转载自p385579058.iteye.com/blog/2219255