天天看點

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