重构一段代码的经历。
源代码,400多行。跳来跳出真心看不懂写的是什么。
主要是把数据加密,写入文件,然后发送给第三方。
按照第三方的给的 dome,你必须 三次文件创建,三次文件写入,三次文件读取。好乱,性能非常差,而且代码杂乱无章,温馨
作为一名有洁癖的程序员,绝对要有统筹,要结构化。
真心不知道,为什么第三方用这么愚蠢的解决方案。我有N种方案处理。但是绝对不会用这么愚蠢的方案。
而
不说,上代码
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.text = text; 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(); } }