`
zxwxiao
  • 浏览: 18904 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics