导读 我们经常遇到,使用http请求发送文件,文件标题乱码(内容正确),这样的情况要怎么解决呢?


项目中的代码大致如下:
最终的结果是,文件上送成功,文件的内容正常,但是文件的标题乱码。

InputStream is = null;
DataOutputStream dos = null;

// 读取文件标题
String fileName = "文件标题";
// (方式1)将字符串直接写入
dos.writeBytes(buildHttpRequest(fileName));

// (方式2)将字符串以字节的形式写入
dos.write(buildHttpRequest(fileName).getBytes());

dos.flush();


// 读取文件内容
is = new FileInputStream("文件File对象");
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1){
    dos.write(buffer,0,len);
}
dos.writeBytes(LINE_END);



// 构建对应的请求信息(不重要)
public String buildHttpRequest(String fileName){
    StringBuffer sb = new StringBuffer();
    sb.append(PREFIX)
    .append(BOUNDARY)
    .append(LINE_END)
    .append("Content-Disposition: form-data; name=\"file\"; filename=\""
            + fileName + "\"" + LINE_END)
    // 文件上送形式
    .append("Content-Type: application/octet-stream" + LINE_END)
    // 文件上送类型
    .append("Content-Transfer-Encoding: binary" + LINE_END)
    .append(LINE_END);
    return sb.toString();
}
 

使用方式1导致出现标题乱码,需要修改为方式2
writeBytes将中文标题中的字符串强转为了byte字节,会丢失精度(char16位,byte8位)。正确处理方式应该是,将String字符串先转化成byte数组,然后使用write方法直接把byte数组进行写入,这样就不会丢失精度了。
writeBytes方法:

public final void writeBytes(String s) throws IOException {
    int len = s.length();
    for (int i = 0 ; i < len ; i++) {
        out.write((byte)s.charAt(i));
    }
    incCount(len);
}
 

write方法:

 public void write(byte b[]) throws IOException {
    write(b, 0, b.length);
}
 

原文来自:https://blog.51cto.com/u_15942107/6019548

本文地址:https://www.linuxprobe.com/http-put-luanma.html编辑:问题终结者,审核员:逄增宝

Linux命令大全:https://www.linuxcool.com/

Linux系统大全:https://www.linuxdown.com/

红帽认证RHCE考试心得:https://www.rhce.net/