1. 程式人生 > >httpClient,流作為檔案上傳

httpClient,流作為檔案上傳

重構一段程式碼的經歷。

原始碼,400多行。跳來跳出真心看不懂寫的是什麼。

主要是把資料加密,寫入檔案,然後傳送給第三方。

按照第三方的給的 dome,你必須  三次檔案建立,三次檔案寫入,三次檔案讀取。好亂,效能非常差,而且程式碼雜亂無章,溫馨

作為一名有潔癖的程式設計師,絕對要有統籌,要結構化。

真心不知道,為什麼第三方用這麼愚蠢的解決方案。我有N種方案處理。但是絕對不會用這麼愚蠢的方案。

 倫理片http://www.dotdy.com/

不說,上程式碼

Java程式碼  收藏程式碼
  1. package com  
  2. import java.io.File;  
  3. import java.io.FileInputStream;  
  4. import java.io.IOException;  
  5. import java.io.OutputStream;  
  6. import org.apache.http.entity.mime.content.FileBody;  
  7. import org.apache.http.util.Args;  
  8. import org.apache.log4j.Logger;  
  9. public class OldFileBody extends FileBody {  
  10.     private static Logger logger = Logger.getLogger(OldFileBody.class
    );  
  11.     private byte[] text;     
  12.     private static File file = new File("");  
  13.     private String fileName ;  
  14.     public OldFileBody(String text,String fileName) {  
  15.         this(text.getBytes(), fileName);  
  16.     }  
  17.     public OldFileBody(byte[] text,String fileName) {  
  18.         super(file);  
  19.         this
    .text = text;  
  20.         this.fileName = fileName;  
  21.     }  
  22.     public long getContentLength() {  
  23.         return this.text.length;  
  24.     }  
  25.     public String getFilename() {  
  26.         return fileName;  
  27.     }  
  28.     public void writeTo(final OutputStream out) throws IOException {  
  29.         Args.notNull(out, "Output stream");  
  30.         out.write(text);  
  31.     }  
  32. }  
  33. CloseableHttpClient httpclient = HttpClientBuilder.create().build();  
  34.         CloseableHttpResponse response = null;  
  35.         try {  
  36.             HttpPost httppost = new HttpPost(url);  
  37.             HttpEntity req = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)  
  38.                     .addPart("files"new OldFileBody(bos.toByteArray(),"de.txt.gz"))  
  39.                     .build();  
  40.             httppost.setEntity(req);  
  41.             response = httpclient.execute(httppost);  
  42.             HttpEntity re = response.getEntity();  
  43.             System.out.println(response.getStatusLine());  
  44.             if (re != null) {  
  45.                 System.out.println(  
  46.                         "Response content: " + new BufferedReader(new InputStreamReader(re.getContent())).readLine());  
  47.             }  
  48.             EntityUtils.consume(re);  
  49.         } finally {  
  50.             try {  
  51.                 response.close();  
  52.             } catch (Exception e) {  
  53.                 e.printStackTrace();  
  54.             }  
  55.         }