Java POST请求 multipart/form-data方式 MultipartFormDataInput解析 参数中文乱码解决方案
1、问题描述:
Java,接收请求,请求方式是:multipart/form-data,接口使用MultipartFormDataInput解析。参数包含form表单参数(String)和文件。在解析时参数中文出现乱码.
2、问题原因:
MultipartFormDataInput解析中InputPart中对编码方式使用了默认值:US-ASCII,因此中文出现乱码。
public interface InputPart {
/**
* If no content-type header is sent in a multipart message part
* "text/plain; charset=ISO-8859-1" is assumed.
* <p>
* This can be overwritten by setting a different String value in
* {@link org.jboss.resteasy.spi.HttpRequest#setAttribute(String, Object)}
* with this ("resteasy.provider.multipart.inputpart.defaultContentType")
* String as key. It should be done in a
* {@link javax.ws.rs.container.ContainerRequestFilter}.
* </p>
*/
String DEFAULT_CONTENT_TYPE_PROPERTY = "resteasy.provider.multipart.inputpart.defaultContentType";
/**
* If there is a content-type header without a charset parameter, charset=US-ASCII
* is assumed.
* <p>
* This can be overwritten by setting a different String value in
* {@link org.jboss.resteasy.spi.HttpRequest#setAttribute(String, Object)}
* with this ("resteasy.provider.multipart.inputpart.defaultCharset")
* String as key. It should be done in a
* {@link javax.ws.rs.container.ContainerRequestFilter}.
* </p>
*/
String DEFAULT_CHARSET_PROPERTY = "resteasy.provider.multipart.inputpart.defaultCharset";
/**
* @return headers of this part
*/
MultivaluedMap<String, String> getHeaders();
String getBodyAsString() throws IOException;
<T> T getBody(Class<T> type, Type genericType) throws IOException;
<T> T getBody(GenericType<T> type) throws IOException;
/**
* @return "Content-Type" of this part
*/
MediaType getMediaType();
/**
* @return true if the Content-Type was resolved from the message, false if
* it was resolved from the server default
*/
boolean isContentTypeFromMessage();
/**
* Change the media type of the body part before you extract it. Useful for specifying a charset.
*
* @param mediaType media type
*/
void setMediaType(MediaType mediaType);
}
3、解决方案
使用InputPart时,手动设置编码方式,改成UTF-8。
import javax.ws.rs.core.MediaType
Map<String, List<InputPart>> formData = hikData.getFormDataMap();
List<InputPart> eventLogs = formData.get("event_log");
InputPart eventLog = eventLogs.get(0);
MediaType mediaType = new MediaType("text", "plain","utf-8");
eventLog.setMediaType(mediaType);
如果是json,我们也可以使用
MediaType mediaType = new MediaType("application", "json","utf-8");
4、解决心得 (原作者的心得)
参考了很多multipart/form-data乱码解决的方案,都没能解决问题,还得自己看源码,找到合适的解决方案。
5、参考资料
https://blog.csdn.net/dangzhizheng/article/details/125682790