
java传输同时附件和普通文本给其它应用接口的方式
发布日期:2021-05-06 17:27:54
浏览次数:30
分类:技术文章
本文共 13617 字,大约阅读时间需要 45 分钟。
在开发中,经常会遇到调用其它系统接口传数据的功能,一般都是穿文本数据,但是偶尔也会有传递附件的接口和普通文本的.
第一种,使用HttpURLConnection
package DownTest;import java.io.BufferedReader;import java.io.ByteArrayOutputStream;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.URL;import java.util.HashMap;import javax.activation.MimetypesFileTypeMap;import org.apache.http.entity.mime.MultipartEntityBuilder;public class FileToInterfaceTest01 { public void formUpload(HashMapparams) { String urlStr = ""; String res = ""; String wf_docnumber="普通文本字段"; String LinkmanEmail="普通文本字段2"; HttpURLConnection conn = null;// boundary就是request头和上传文件内容的分隔符 String BOUNDARY = "---------------------------123821742118716"; try { URL url = new URL(urlStr); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(30000); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); OutputStream out = new DataOutputStream(conn.getOutputStream());// text StringBuffer strBuf = new StringBuffer(); strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n"); strBuf.append("Content-Disposition:form-data;name=\"wf_docnumber\"\r\n\r\n"); strBuf.append(wf_docnumber); strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n"); strBuf.append("Content-Disposition:form-data;name=\"LinkmanEmail\"\r\n\r\n"); strBuf.append(LinkmanEmail); out.write(strBuf.toString().getBytes());// file String filePath = ""; MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create(); // ContentType contentType = ContentType.create("text/plain", // Charset.forName("UTF-8")); // ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, // HTTP.UTF_8); /* 读取文件 */ File file = new File(filePath); // file.name String filename=""; /* 如果文件存在 */ if (file.exists()) { String contentType = new MimetypesFileTypeMap().getContentType(file); contentType = "application/octet-stream"; // contentType="application/x-www-form-urlencoded"; StringBuffer strBuf2 = new StringBuffer(); strBuf2.append("\r\n").append("--").append(BOUNDARY).append("\r\n"); strBuf2.append("Content-Disposition:form-data;name=\"items\";filename=\"" + filename + "\"\r\n"); strBuf2.append("Content-Type:" + contentType + "\r\n\r\n"); out.write(strBuf2.toString().getBytes()); DataInputStream in = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = in.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } in.close(); } else { System.out.println("Error: can't find the file " + filename); } byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(); out.write(endData); out.flush(); out.close();// 读取返回数据 StringBuffer strBuf3 = new StringBuffer(); InputStream inputStream = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line = null; while ((line = reader.readLine()) != null) { strBuf3.append(line).append("\n"); } res = strBuf3.toString(); reader.close(); reader = null; } catch (Exception e) { System.out.println("发送POST请求出错。e=" + e); InputStream inputStream = conn.getErrorStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();// 自带缓存的输出流 String str = ""; /// String str2=""; int len = -1; byte[] buffer = new byte[1024]; try { while ((len = inputStream.read(buffer)) != -1) { baos.write(buffer, 0, len); // 将读到的字节,写入baos // str2+=new String(buffer); } str = new String(baos.toByteArray(), "utf-8"); System.out.println(str); } catch (IOException e1) { e.printStackTrace(); } e.printStackTrace(); } finally { if (conn != null) { conn.disconnect(); conn = null; } } System.out.println(res); }}
第一种写起来太麻烦,使用HttpClient要方便多了
package DownTest;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.InputStream;import java.nio.charset.Charset;import org.apache.http.HttpEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpPost;import org.apache.http.conn.ssl.SSLConnectionSocketFactory;import org.apache.http.conn.ssl.SSLContextBuilder;import org.apache.http.conn.ssl.TrustSelfSignedStrategy;import org.apache.http.entity.ContentType;import org.apache.http.entity.mime.HttpMultipartMode;import org.apache.http.entity.mime.MultipartEntityBuilder;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;/** * java传递附件给接口 * * */public class FileToInterfaceTest02 { public void send() throws Exception { String url = ""; String res = ""; String wf_docnumber = "普通文本字段"; String LinkmanEmail = "普通文本字段2"; MultipartEntityBuilder fileList = getAttachmentsNameAndPath(); fileList.setCharset(java.nio.charset.Charset.forName("UTF-8")); fileList.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // BeanCtx.p(fileList); fileList.addTextBody("receiverMails", LinkmanEmail, ContentType.MULTIPART_FORM_DATA); fileList.addTextBody("wf_docnumber", wf_docnumber, ContentType.MULTIPART_FORM_DATA); SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory(builder.build()); CloseableHttpClient http = HttpClients.custom().setSSLSocketFactory(sslFactory).build(); String list = postSend(fileList, url, http); System.out.println(list); } public MultipartEntityBuilder getAttachmentsNameAndPath() throws Exception { MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create(); ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8")); // ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, // HTTP.UTF_8); String filePath = ""; /* 读取文件 */ File file = new File(filePath); // file.name /* 如果文件存在 */ if (file.exists()) { int fileLength = (int) file.length(); /* 如果文件长度大于0 */ if (fileLength != 0) { /* 创建输入流 */ InputStream inStream = new FileInputStream(file); byte[] buf = new byte[4096]; /* 创建输出流gjjj */ ByteArrayOutputStream bos = new ByteArrayOutputStream(1024); byte[] b = new byte[1000]; int readLength; while (((readLength = inStream.read(buf)) != -1)) { bos.write(buf, 0, readLength); } inStream.close(); byte[] data = bos.toByteArray(); bos.close(); // application/x-www-form-urlencoded。 reqEntity.addBinaryBody("file", data, ContentType.MULTIPART_FORM_DATA, file.getName()); // StringBody stringBody = new // StringBody(doc.g("WF_OrUnid")+":"+downloadfilename, contentType); // reqEntity.addPart("fileName", stringBody); // fileList.add(map); } } // return fileList; return reqEntity; } public String postSend(MultipartEntityBuilder map, String url, CloseableHttpClient http) throws Exception { // System.out.println("url="+url); String body = ""; String encoding = "utf-8"; HttpPost httpPost = new HttpPost(url); httpPost.setEntity(map.build()); httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); // 执行请求操作,并拿到结果(同步阻塞) CloseableHttpResponse response = http.execute(httpPost); // 获取结果实体 HttpEntity entity = response.getEntity(); if (entity != null) { // 按指定编码转换结果实体为String类型 body = EntityUtils.toString(entity, encoding); } response.close(); return body; }}
上面两种虽然写法不同,但是其实是一样,都是模拟前端表单上传附件的形式,接口接收时是接收对应的io流.
第三种,直接将文件读出来byte[],然后利用base64编码将byte[]转成string,组成json字符串传给接口方.接口方解析json字符串,根据key获取对于的文件数据,利用base64转码成byte[],再将byte[]写到本地就行.当然,编码和解码一定要配套,否则会导致文件传输出错.package DownTest;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.nio.charset.Charset;import java.util.ArrayList;import java.util.Base64;import java.util.HashMap;import java.util.List;import java.util.Map;import org.apache.http.HttpEntity;import org.apache.http.NameValuePair;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpPost;import org.apache.http.conn.ssl.SSLConnectionSocketFactory;import org.apache.http.conn.ssl.SSLContextBuilder;import org.apache.http.conn.ssl.TrustSelfSignedStrategy;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.message.BasicNameValuePair;import org.apache.http.protocol.HTTP;import org.apache.http.util.EntityUtils;import com.alibaba.fastjson.JSONArray;/** * java传递附件给接口 * * */public class FileToInterfaceTest03 { public void send() throws Exception { String url = ""; String res = ""; String wf_docnumber = "普通文本字段"; String LinkmanEmail = "普通文本字段2"; List
发表评论
最新留言
初次前来,多多关照!
[***.217.46.12]2025年03月31日 22时41分44秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
Scala_1.控制台打印,变量定义,函数定义
2021-05-07
Linux Vim操作-添加行号
2021-05-07
十五.Python异常处理
2019-03-04
c++备考期末必须看的知识点(一篇就够了)
2019-03-04
qt中初始化界面的几种方法
2019-03-04
【图论】游乐场
2019-03-04
【图论】【最短路】USACO 2.4 牛的旅行 (最短路)
2019-03-04
【图论】【最短路】工厂的烦恼
2019-03-04
【图论】刻录光盘
2019-03-04
03-C语言进阶——模拟实现字符串操作函数
2019-03-04
C语言初阶——指针
2019-03-04
[88]. 合并两个有序数组(C语言)
2019-03-04
docker部署Hadoop环境
2019-03-04
最全环境搭建-常用软件安装
2019-03-04
Linux 安装 MySql
2019-03-04
系统架构
2019-03-04
网关程序的开发
2019-03-04
SpringBoot(Spring IOC 和 Spring MVC)(待补充)
2019-03-04
复制字符数组
2019-03-04
变量命名的通用规则
2019-03-04