最近利用httpclient来做模拟表单提交的程序,发现这个咚咚对中文的支持实在是差,查看源码后发现问题出现
在org/apache/commons/httpclient/util这个包里的encodingutil.java,和org/apache/commons/httpclient/methods/multipart这个包里的stringpart.java及filepart.java这三个类里面。
先说说encodingutil这个类,虽然你可以在第50行看到
private static final string default_charset = "iso-8859-1";
这样的定义,但你在往下看就会发现getasciibytes(final string data)这个里并没有用这定义的编码来对数据进行encoding.而是用了us-ascii码来进行encoding的。程序如下:
public static byte[] getasciibytes(final string data) {
if (data == null) {
throw new illegalargumentexception("parameter may not be null");
}
try {
return data.getbytes("us-ascii"); //就是这一句拉
} catch (unsupportedencodingexception e) {
throw new httpclienterror("httpclient requires ascii support");
}
}
把编码该成你自己想要的吧。在这里解决了上传文件名为中文的问题。接下来解决field字段内容为中文的的问题
修改stringpart中58行:
public static final string default_charset = "us-ascii";
同理,改成你自己想要的编码
然后重新编译打包。记得把logging 和codec 这两个包引进项目里。否则编译会出一堆错误。
其实在stringpart这个类里是提供了自定义编码格式的方法。可是在filepart类里没有实现而已。
第79行:
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;
}
你可以在filepart里把这个方法实现了。这样你就可以指定编码格式提交表单了。个人觉得这个方法比修改默认编码强。灵活性高些。
其实我只想模拟表单提交,在applet中实现文件上传,本想偷懒不自己写模拟表单提交这块的。用了httpclient这个开源包。可是打完applet的jar包发现这个包竟然350多k。让我非常的郁闷。看来还是需要自己写模拟表单实现提交了。起码打完包也不会超过20k。
如果需要转载,请注明出处和作者。谢谢
qq:221704
msn:flyly@yeah.net
email:zhangfl@sports.cn
闽公网安备 35060202000074号