java小知识:http请求传输文件流
前文:项目里要给第三方传输图片,对方接口要求传文件流,而不是常用的base64编码,在此记录一下~
直接贴代码吧:
import com.alibaba.fastjson.JSONObject;
import com.leyue100.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;import javax.activation.MimetypesFileTypeMap;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;@Slf4j
public class FileUploadUtil {public static void main(String[] args) {try {Map<String, String> filePathMap = new HashMap<>();String url = "";filePathMap.put("2345678", "/上传.jpg");String result = fileUpload(url, "id","2345",filePathMap");log.info("影像上传接口返回参数" + JSONObject.toJSONString(result));} catch (Exception e) {log.error("财信上传文件系统异常!fileUpload", e);throw e;}}/*** 影像上传接口** @param relaid*/public static String fileUpload(String url, String seqId, String imgList, Map<String, String> fileMap) {try {Map<String, Object> textMap = new HashMap<String, Object>();//可以设置多个input的name,valuetextMap.put("seqId", seqId);textMap.put("imglist", imgList);log.info("上传接口请求参数" + textMap.toString());String result = formUpload(url, textMap, fileMap, ".jpg");log.info("上传接口返回参数" + JSONObject.toJSONString(result));return result;} catch (Exception e) {log.error("上传文件系统异常!fileUpload", e);throw e;}}/*** 功能描述:删除已经上传的文件** @author songchengye* @date 2022/4/8 下午6:18*/public static void removeFile(Map<String, String> fileMap) {if (fileMap != null) {Iterator iter = fileMap.entrySet().iterator();while (iter.hasNext()) {Map.Entry entry = (Map.Entry) iter.next();String inputValue = (String) entry.getValue();if (inputValue == null) {continue;}File file = new File(inputValue);file.delete();}}}@SuppressWarnings("rawtypes")public static String formUpload(String urlStr, Map<String, Object> textMap,Map<String, String> fileMap, String contentType) {String res = "";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("requestId", StringUtils.getLyRandomUUID());conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);OutputStream out = new DataOutputStream(conn.getOutputStream());// textif (textMap != null) {StringBuffer strBuf = new StringBuffer();Iterator iter = textMap.entrySet().iterator();while (iter.hasNext()) {Map.Entry entry = (Map.Entry) iter.next();String inputName = (String) entry.getKey();String inputValue = (String) entry.getValue();if (inputValue == null) {continue;}strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");strBuf.append(inputValue);}out.write(strBuf.toString().getBytes());}// fileif (fileMap != null) {Iterator iter = fileMap.entrySet().iterator();while (iter.hasNext()) {Map.Entry entry = (Map.Entry) iter.next();String inputName = (String) entry.getKey();String inputValue = (String) entry.getValue();if (inputValue == null) {continue;}File file = new File(inputValue);String filename = file.getName();//没有传入文件类型,同时根据文件获取不到类型,默认采用application/octet-streamcontentType = new MimetypesFileTypeMap().getContentType(file);//contentType非空采用filename匹配默认的图片类型if (!"".equals(contentType)) {if (filename.endsWith(".png")) {contentType = "image/png";} else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {contentType = "image/jpeg";} else if (filename.endsWith(".gif")) {contentType = "image/gif";} else if (filename.endsWith(".ico")) {contentType = "image/image/x-icon";}}if (contentType == null || "".equals(contentType)) {contentType = "application/octet-stream";}StringBuffer strBuf = new StringBuffer();strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");// strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");strBuf.append("Content-Type:" + contentType + "\r\n\r\n");out.write(strBuf.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();}}byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();out.write(endData);out.flush();out.close();// 读取返回数据StringBuffer strBuf = new StringBuffer();BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));String line = null;while ((line = reader.readLine()) != null) {strBuf.append(line).append("\n");}res = strBuf.toString();reader.close();reader = null;} catch (Exception e) {System.out.println("发送POST请求出错。" + urlStr);e.printStackTrace();} finally {if (conn != null) {conn.disconnect();conn = null;}}return res;}}
就不在这里写单元测试了,有不明白的可以留言。。。
java小知识:http请求传输文件流相关推荐
- 【java小知识】FileReader读取文件出现乱码的解决办法
转1:https://blog.csdn.net/a532672728/article/details/79432619 转2:https://www.cnblogs.com/qq78292959/p ...
- python传文件给java_用java pyhont通过HTTP协议传输文件流
// 代码网上抄的 忘记链接了 抱歉哈 packageupload;importjava.io.BufferedReader;importjava.io.DataOutputStream;import ...
- java小兔跳铃铛,Java小知识 - 顾小兔2018的个人空间 - OSCHINA - 中文开源技术交流社区...
Java小知识 [TOC] (1)三种读取文件方法 URL url = this.getClass ().getResource ("/a.txt"); Resources.asC ...
- java scp发送文件到服务器,Java实现往远程服务器传输文件
Java实现往远程服务器传输文件 内容精选 换一换 已成功登录Java性能分析.待安装Guardian的服务器已开启sshd.待安装Guardian的服务器已安装JRE,JRE版本要求为Huawei ...
- php接收流文件,PHP传输文件流及文件流的保存
什么是文件流 在HTTP数据传送过程中,传输一方直接以二进制流方式传送文件内容,这样就形成了一个文件流: 文件流的接收通常涉及到预定义变量函数 $HTTP_RAW_POST_DATA 和 file_g ...
- 【Java】每日一点Java小知识 --- day6
每日一点Java基础小知识 - day6 欢迎来到叮当猫学编程的Java基础小知识系列~在这里,你将会看到叮当猫每日关于Java的基础知识总结,欢迎大家的点赞关注喔 方法重载: 被重载的方法必须改变参 ...
- Java中IO(一、文件流)
文件流 FileInputStream从文件系统中的文件获取输入字节.哪些文件可用取决于主机环境. FileInputStream用于读取原始字节流,如图像数据.要读取字符流,请考虑使用FileRea ...
- 《Java两台电脑之间传输文件》
开发工具与关键技术:IDEA Java 撰写时间:2021/8/10 讲解一下两台电脑之间通过java代码传输视频文件(在有网络的情况下),我通过TCP协议来完成操作 ,TCP协议要明确哪一台电 ...
- 上午小博(java小知识)
使用super来引用父类的成分,使用this来引用当前对象 一个类从另一个类继承,new这个子类的实例的时候,使用super来引用父类对象,this是指当前对象的引用. 当new一个对象出来的时候,这 ...
最新文章
- 2019年十大数据与分析技术趋势
- 数学 —— 巧用进制
- 大量DelegatingClassLoader类加载器,导致Perm区溢出
- amazon alexa_亚马逊使向自定义Alexa Skills添加声音变得更加容易
- c#与api类型对照表
- Tomcat配置可以访问外部资源路径
- 字典dictionary
- JavaScript螺纹的问题和答案
- 7-5 猴子选大王 (20 分)
- Linux入门-第四周
- html js 处理元素的数据属性(data)
- 线性调频信号及仿真[python]
- 易用宝项目记录day7-权限与菜单
- 微信公众号管理后台获取已关注的openid
- 公共DNS递归服务器(转发)
- (OK) 股市财经博客参考!
- 关于信号强度单位db和dBm
- ucharts 柱状图圆角_调整柱状图圆角弧度
- 怎么用按键精灵快速开发计算距离自己最近的怪物/包裹/金矿坐标的脚本
- 一张纸(5毫米)折叠多少次可以达到珠穆朗玛峰的高度(8848米)?