标签:
http上传文件方法,使用post方式上传文件会因为文件的编码问题而存在中文乱码的问题,通过方法 codeString() 来获得编码格式,在自定义的 CustomFilePart() 中得到对应的格式,从而保证格式的一致性,不出现乱码。
private void httpUpload(String url, String filepath, EssFileServer essFileServer) { File targetFile = new File(filepath); //判断文件的编码格式 final String code = codeString(filepath); PostMethod filePost = new PostMethod(url){ public String getRequestCharSet() { return code; } }; try { Part[] parts = new Part[]{ new CustomFilePart(targetFile.getName() , targetFile) }; filePost.setRequestEntity(new MultipartRequestEntity(parts ,filePost.getParams())); HttpClient client = new HttpClient(); // 设置http服务器的登陆用户名和密码 UsernamePasswordCredentials creds = new UsernamePasswordCredentials( essFileServer.getUsername(), essFileServer.getPsw()); client.getState().setCredentials(AuthScope.ANY, creds); // 设置超时时间 client.getHttpConnectionManager().getParams().setConnectionTimeout(10000); client.executeMethod(filePost); } catch (Exception e) { e.printStackTrace(); } finally { filePost.releaseConnection(); } }
CustomFilePart.java
public class CustomFilePart extends FilePart { private String code; public CustomFilePart(String filename, File file) throws FileNotFoundException { super(filename, file); code = HttpClientManager.codeString(file.toString()); } protected void sendDispositionHeader(OutputStream out) throws IOException { super.sendDispositionHeader(out); String filename = getSource().getFileName(); if (filename != null) { out.write(EncodingUtil.getAsciiBytes(FILE_NAME)); out.write(QUOTE_BYTES); out.write(EncodingUtil.getBytes(filename, code)); out.write(QUOTE_BYTES); } } }
codeString() 判断编码格式的方法,在网上找的,也就懒得改了
/** * 判断文件的编码格式 * @param fileName :file * @return 文件编码格式 */ public static String codeString(String fileName) { int p = 0; String code = ""; BufferedInputStream bin = null; try { bin = new BufferedInputStream(new FileInputStream(fileName)); p = (bin.read() << 8) + bin.read(); code = null; } catch (Exception e) { e.printStackTrace(); } finally { if(null != bin) { try { bin.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } switch (p) { case 0xefbb: code = "UTF-8"; break; case 0xfffe: code = "Unicode"; break; case 0xfeff: code = "UTF-16BE"; break; default: code = "GBK"; } } return code; }
这样就能解决上传文件中文乱码的问题
使用http下载文件时会出现有空格而无法下载的情况,解决办法对空格进行转译
if(path != null && path.contains(" ")) { path = path.replaceAll(" ", "%20"); }
笔记,随时更新
标签:
原文地址:http://my.oschina.net/u/2002410/blog/511076