问题
I'm using FormHttpMessageConverter in Spring Framework. For sending a file by restTemplate, I added FormHttpMessageConverter in my project.
The problem is the server where takes the file asked string encrypted Content-type of me. I had to send the file with Content-type: multipart/form-data, but they asked "Content-type: multipart/form-data;" and "boundary:XXXX".
So I tried to make a value for boundary before send the file. However, the boundary value was overwritted when RestTemplate.exchage() The reason was FormHttpMessageConverter. FormHttpMessageConverter caught the request for converting. If Content-type is multipart/form-data, FormHttpMessageConverter overwrites boundary value by this code.
https://github.com/spring-projects/spring-framework/blob/5f4d1a4628513ab34098fa3f92ba03aa20fc4204/spring-web/src/main/java/org/springframework/http/converter/FormHttpMessageConverter.java#L336
I couldn't find the way to avoid this problem, so I copied that code at the link, and made a file "xxxFormHttpMessageConverter" and modified the method "writeMultipart".
Do someone know how to avoid this overwriting?
回答1:
In Spring boot you can customize boundary by creating a new HttpMessageConverter bean. And Spring boot will replace the older one automaticlly. The code looks like this:
@Configuration
public class CustomerHttpMessageConverter {
public static final String MY_BOUNDARY = "XXXXXXXX";
@Bean
public HttpMessageConverter<MultiValueMap<String, ?>> createCustomerFormHttpMessageConverter() {
return new CustomerFormHttpMessageConverter();
}
static class CustomerFormHttpMessageConverter extends FormHttpMessageConverter {
@Override
protected byte[] generateMultipartBoundary() {
return MY_BOUNDARY.getBytes(Charset.forName("UTF-8"));
}
}
}
You can find more information here.
来源:https://stackoverflow.com/questions/45401043/boundary-in-contenty-type-is-overwritten-by-formhttpmessageconverter