HttpClient Post中文問題解決

在利用httpclient向服務器post數據時,有兩種中文問題;

1.filed字段值的中文

2.file名的中文

對於第一種,參看StringPart;其源代碼有這樣一段:

    private byte[] getContent() {
        if (content == null) {
            content = EncodingUtil.getBytes(value, getCharSet());
        }
        return content;
    }
    
    protected void sendData(OutputStream out) throws IOException {
        LOG.trace("enter sendData(OutputStream)");
        out.write(getContent());
    }

可以看出在發送數據時其調用了EncodingUtil的getBytes方法(利用了你通過setCharSet設置的編碼)

因此,只要你在代碼中這樣:

   StringPart part = new StringPart(name, value);

   part.setCharSet("GBK");

中文就沒有問題了

對於第二種,參看FilePart;其源代碼中有這樣一段:

protected void sendDispositionHeader(OutputStream out) 
    throws IOException {
        LOG.trace("enter sendDispositionHeader(OutputStream out)");
        super.sendDispositionHeader(out);
        String filename = this.source.getFileName();
        if (filename != null) {
            out.write(FILE_NAME_BYTES);
            out.write(QUOTE_BYTES);
            out.write(EncodingUtil.getAsciiBytes(filename));
            out.write(QUOTE_BYTES);
        }
    }

可以看出在轉換文件名時,用的方法是EncodingUtil.getAsciiBytes(),查看這個方法源碼爲data.getBytes("US-ASCII"),因此中文文件名必定亂碼,不管你是否調用了setCharSet("GBK")方法。

解決很簡單:

   out.write(EncodingUtil.getBytes(filename, getCharSet()));

看了網上好多文章,好多都說改EncodingUtil類,其實我覺得改FilePart更好一些

發佈了63 篇原創文章 · 獲贊 2 · 訪問量 8280
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章