首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 操作系统 >

PostMethod提交带有附件的的form乱码有关问题解决

2014-06-01 
PostMethod提交带有附件的的form乱码问题解决主题,直接重点:

PostMethod提交带有附件的的form乱码问题解决

主题,直接重点:

=====================================================================

通常会直接如下这样写:

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

热点排行