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(HashMap
params) { 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
> items = getFileStr(); // BeanCtx.p("items=" + items); Map
map = new HashMap
(); map.put("items", items); map.put("receiverMails", LinkmanEmail); map.put("wf_docnumber", wf_docnumber); List
pairs = new ArrayList
(); pairs.add(new BasicNameValuePair("receiverMails", LinkmanEmail)); pairs.add(new BasicNameValuePair("wf_docnumber", wf_docnumber)); pairs.add(new BasicNameValuePair("items", JSONArray.toJSONString(items))); 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(map, url, http); System.out.println(list); } /** * 文件转化成base64字符串 将文件转化为字节数组字符串,并对其进行Base64编码处理 */ public List
> getFileStr() { // ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, // HTTP.UTF_8); List
> items = new ArrayList
>(); String filePath = ""; File file = new File(filePath); // file.name String fileName = ""; /* 如果文件存在 */ if (file.exists()) { Map
map = new HashMap
(); int fileLength = (int) file.length(); /* 如果文件长度大于0 */ if (fileLength != 0) { /* 创建输入流 */ InputStream in = null; byte[] data = null; // 读取文件字节数组 try { in = new FileInputStream(file); data = new byte[in.available()]; in.read(data); in.close(); } catch (IOException e) { e.printStackTrace(); } finally { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } // 对字节数组Base64编码 // BASE64Encoder encoder = new BASE64Encoder(); // 对字节数组Base64编码 // 返回 Base64 编码过的字节数组字符串 String fileStr = toBase64String(data);// encoder.encode(data); map.put("fileName", fileName); map.put("file", fileStr); items.add(map); } } return items; /* * InputStream in = null; byte[] data = null; // 读取文件字节数组 try { in = new * FileInputStream(filePath); data = new byte[in.available()]; in.read(data); * in.close(); } catch (IOException e) { e.printStackTrace(); } finally { try { * in.close(); } catch (IOException e) { e.printStackTrace(); } } */ } public String toBase64String(byte[] source) { // return Base64.getEncoder().encodeToString(source); return Base64.getEncoder().encodeToString(source).replaceAll("\r\n", "").replaceAll("\r", "").replaceAll("\n", ""); // Base64.encodeBase64String(source).replaceAll("\r\n", "").replaceAll("\r", // "").replaceAll("\n", ""); }// json字符串传递数据 public String postSend(Map
map, String url, CloseableHttpClient http) throws Exception { // System.out.println("url="+url);// BeanCtx.p("
参数=" + JSONArray.toJSONString(map)); String body = ""; String encoding = "utf-8"; HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new StringEntity(JSONArray.toJSONString(map), Charset.forName("UTF-8"))); httpPost.setHeader("Content-type", "application/json;charset=utf-8"); 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; }// NameValuePair传递 public String postSend(List
pairs, String url, CloseableHttpClient http) throws Exception { // System.out.println("url="+url); String body = ""; String encoding = "utf-8"; HttpPost httpPost = new HttpPost(url);//"application/x-www-form-urlencoded" httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded"); // 4.添加参数 httpPost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8)); // httpPost.setHeader("Content-type", "application/json;charset=utf-8"); 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; }}
上一篇:linux使用yum安装软件报错
下一篇:echarts统计图保存成图片,兼容IE

发表评论

最新留言

初次前来,多多关照!
[***.217.46.12]2025年03月31日 22时41分44秒