httpClient,流作為檔案上傳
阿新 • • 發佈:2019-01-10
重構一段程式碼的經歷。
原始碼,400多行。跳來跳出真心看不懂寫的是什麼。
主要是把資料加密,寫入檔案,然後傳送給第三方。
按照第三方的給的 dome,你必須 三次檔案建立,三次檔案寫入,三次檔案讀取。好亂,效能非常差,而且程式碼雜亂無章,溫馨
作為一名有潔癖的程式設計師,絕對要有統籌,要結構化。
真心不知道,為什麼第三方用這麼愚蠢的解決方案。我有N種方案處理。但是絕對不會用這麼愚蠢的方案。
而
倫理片http://www.dotdy.com/
不說,上程式碼
Java程式碼- package com
- import java.io.File;
-
import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.OutputStream;
- import org.apache.http.entity.mime.content.FileBody;
- import org.apache.http.util.Args;
- import org.apache.log4j.Logger;
- public class OldFileBody extends FileBody {
-
private static Logger logger = Logger.getLogger(OldFileBody.class
- private byte[] text;
- private static File file = new File("");
- private String fileName ;
- public OldFileBody(String text,String fileName) {
- this(text.getBytes(), fileName);
- }
- public OldFileBody(byte[] text,String fileName) {
- super(file);
-
this
- this.fileName = fileName;
- }
- public long getContentLength() {
- return this.text.length;
- }
- public String getFilename() {
- return fileName;
- }
- public void writeTo(final OutputStream out) throws IOException {
- Args.notNull(out, "Output stream");
- out.write(text);
- }
- }
- CloseableHttpClient httpclient = HttpClientBuilder.create().build();
- CloseableHttpResponse response = null;
- try {
- HttpPost httppost = new HttpPost(url);
- HttpEntity req = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
- .addPart("files", new OldFileBody(bos.toByteArray(),"de.txt.gz"))
- .build();
- httppost.setEntity(req);
- response = httpclient.execute(httppost);
- HttpEntity re = response.getEntity();
- System.out.println(response.getStatusLine());
- if (re != null) {
- System.out.println(
- "Response content: " + new BufferedReader(new InputStreamReader(re.getContent())).readLine());
- }
- EntityUtils.consume(re);
- } finally {
- try {
- response.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }