使用 httpcomponents httpclient上传文件时客户端发送的 http Content-Type:
Content-Type: multipart/form-data; boundary=rxU1IcP2kHsJVF37W5_8tRtSlAnB-KIhGP; charset=UTF-8
jfinal 4.9.01 解析方法如下:
/**
* Extracts and returns the boundary token from a line.
*
* @return the boundary token.
*/
private String extractBoundary(String line) {
// Use lastIndexOf() because IE 4.01 on Win98 has been known to send the
// "boundary=" string multiple times. Thanks to David Wall for this fix.
int index = line.lastIndexOf("boundary=");
if (index == -1) {
return null;
}
String boundary = line.substring(index + 9); // 9 for "boundary="
if (boundary.charAt(0) == '"') {
// The boundary is enclosed in quotes, strip them
index = boundary.lastIndexOf('"');
boundary = boundary.substring(1, index);
}
// The real boundary is always preceeded by an extra "--"
boundary = "--" + boundary;
return boundary;
}无法正确解析出boundary,会带上“;charset=UTF-8”的内容。
解决方法1:
修改httpclient上传代码:注释编码设置的地方
MultipartEntityBuilder.create() //.setCharset(Consts.UTF_8) ...
如上所示,注释掉 setCharset 那一行客户端发送的 Content-Type 就没有 "charset=UTF-8" 了,就可以正常上传了。
解决方法2:
重写jfinal中com.oreilly.servlet.multipart.MultipartParser代码,将方法extractBoundary改成如下代码即可完美解析boundary内容
/**
* Extracts and returns the boundary token from a line.
*
* @return the boundary token.
*/
private String extractBoundary(String line) {
// Use lastIndexOf() because IE 4.01 on Win98 has been known to send the
// "boundary=" string multiple times. Thanks to David Wall for this fix.
String[] lines = line.split(";");
for (String lin : lines) {
int index = lin.lastIndexOf("boundary=");
if (index == -1) {
continue;
}
String boundary = lin.substring(index + 9); // 9 for "boundary="
if (boundary.charAt(0) == '"') {
// The boundary is enclosed in quotes, strip them
index = boundary.lastIndexOf('"');
boundary = boundary.substring(1, index);
}
// The real boundary is always preceeded by an extra "--"
boundary = "--" + boundary;
return boundary;
}
return null;
}