天天看点

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"),

原因:

查看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