HttpClient4.2.5 上传中文文件名乱码

示例:使用httpclient4.2.5.jar 上传图片,后台servlet中使用commons-fileupload-1.3.jar 处理上传文件

注意版本问题:使用httpclient4.2.5,httpmime-4.2.5.jar,httpmime-4.2.5.jar上传后

后台:

ServletFileUpload upload = new ServletFileUpload(diskFactory);

List fileItems = upload.parseRequest(request);

fileItems的结果集始终等于0,然后测试采用jsp上传,发现上传控件<input type="file" name="d" />

中name属性不能为空,否则fileItems的结果集始终为0。

httpclient 调试的过程中发现,这个文件名是放在head里的

form-data; name="d"; filename="中心.jpg"{org.apache.http.entity.mime.FormBodyPart类中封装}

 

在org.apache.http.entity.mime.HttpMultipart类中调用了这个方法(需要修改源码):

 

  private static void writeField( final MinimalField field, final OutputStream out) throws IOException {

        writeBytes(field.getName(), out);

        writeBytes(FIELD_SEP, out);

        writeBytes(field.getBody(), out); // 此处没有进行charset 修改为writeBytes(field.getBody(),Charset.forName("UTF-8"), out);

        writeBytes(CR_LF, out);

    }

开始调用方式:

File file = new File("D:\\test\\upload\\中心.jpg");

HttpPost post = new HttpPost(“http://localhost:8088/WebService/a/d.do”);

MultipartEntity reqEntity = new MultipartEntity();

StringBody comment = new StringBody("A binary啦", Charset .forName(org.apache.http.protocol.HTTP.UTF_8));

reqEntity.addPart("a1", bin);

reqEntity.addPart("a2", comment);

post.setEntity(reqEntity);

HttpResponse response = client.execute(post);

HttpEntity resEntity = response.getEntity();

 

说明在执行client.execute(post);的过程中会调用reqEntity.writeTo(OutputStream d);方法,方法如下

 public void writeTo(final OutputStream outstream) throws IOException {

        this.multipart.writeTo(outstream);

 

    }

 

最后发现其实可以不用改源码的

MultipartEntity d = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,null,Charset.forName("UTF-8"));

 

HttpMultipartMode.BROWSER_COMPATIBLE 枚举值

因为程序默认是HttpMultipartMode.STRICT 所以走的是没有转化字符集的方法。

over

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值