httpclient上傳文件的文件名的中文問題
在利用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更好一些
最後更新:2017-04-03 20:19:50