主题,直接重点:
=====================================================================
通常会直接如下这样写:
Part[] parts = {
new StringPart("name", "HelloWorld,小单"),
new FilePart("file", new File("e:\\resume.doc"))
};
PostMethod mPost = new PostMethod(url);
mPost.setRequestEntity(new MultipartRequestEntity(parts, mPost.getParams()));
int status = httpClient.executeMethod(mPost);
不出意外的话,会出乱码 ^_^
做如下修改,在new StringPart方法中增加参数,charset
Part[] parts = {
new StringPart("name", "HelloWorld,小单", "UTF-8"),
new FilePart("file", new File("e:\\resume.doc"))
};
原因:
查看StringPart源码,如下:
/** Default charset of string parameters*/
public static final String DEFAULT_CHARSET = "US-ASCII";
public StringPart(String name, String value, String charset) {
super(
name,
DEFAULT_CONTENT_TYPE,
charset == null ? DEFAULT_CHARSET : charset,
DEFAULT_TRANSFER_ENCODING
);
if (value == null) {
throw new IllegalArgumentException("Value may not be null");
}
if (value.indexOf(0) != -1) {
// See RFC 2048, 2.8. "8bit Data"
throw new IllegalArgumentException("NULs may not be present in string parts");
}
this.value = value;
}
如不指定charset,则会使用默认编码“US-ASCII”。
PS:我用的jar包为 commons-httpclient-3.1.jar