通过InputStreamResource下载上传图片
1.封装post接口类,需要注意的是Content-Disposition,file和filename根据实际接口进行调整
public static String sendPostFile(String requestUrl,Map<String, String> requestHeader, Map<String, InputStreamResource> fileParams) throws Exception {
HttpURLConnection conn=null;
StringBuilder response=new StringBuilder();
try{
URL realUrl = new URL(requestUrl);
conn = (HttpURLConnection) realUrl.openConnection();
conn.setRequestMethod(“POST”);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
if (requestHeader != null && requestHeader.size() > 0) {
for (Entry<String, String> entry : requestHeader.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
conn.setRequestProperty(“Connection”,“keep-Alive”);
conn.setRequestProperty(“Charset”,“UTF-8”);
conn.setRequestProperty(“Accept-Charset”,“UTF-8”);
String boundary = “--------POST件–文件----------------” + String.valueOf(new Date().getTime());
conn.setRequestProperty(“Content-Type”,“multipart/form-data; charset=UTF-8; boundary=” + boundary);
DataOutputStream dos=new DataOutputStream(conn.getOutputStream());
if(fileParams!=null&&!fileParams.isEmpty()){
for (Entry<String, InputStreamResource> entry : fileParams.entrySet()) {
StringBuilder fileSb=new StringBuilder();
fileSb.append("--").append(boundary).append("\r\n")
.append("Content-Disposition: form-data; name=\"file\"; filename=\"blob\""+"\r\n")
.append("Content-Type: multipart/form-data; charset=UTF-8"+"\r\n")
.append("Content-Transfer-Encoding:8bit"+"\r\n")
.append("\r\n");
dos.write(fileSb.toString().getBytes("UTF-8"));
System.out.println(fileSb.toString());
dos.flush();
InputStream is=entry.getValue().getInputStream();
byte[] buffer=new byte[1024];
int len=0;
while ((len= is.read(buffer))!=-1){
dos.write(buffer,0,len);
}
is.close();
dos.writeBytes("\r\n");
}
String end="--" + boundary + "--\r\n";
dos.write(end.getBytes(StandardCharsets.UTF_8));
dos.flush();
dos.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line=null;
while ((line=reader.readLine())!=null){
response.append(line);
}
}
} catch (Exception e) {
e.printStackTrace();
return POST_CATCH;
} finally {
if(conn!=null){
conn.disconnect();
}
}
return response.toString();
}
2. 接口请求返回的图片直接用InputStream进行接收
public static InputStream sendGetInput(String requestUrl, Map<String, String> requestHeader, String responseEncoding) throws IOException {
String result = "";
BufferedReader reader = null;
InputStream input = null;
// File w2 = null;
try {
if (requestUrl == null || requestUrl.isEmpty()) {
return null;
}
URL realUrl = new URL(requestUrl);
URLConnection connection = realUrl.openConnection();
connection.setRequestProperty(“accept”, “text/html, application/xhtml+xml, image/jxr, /”);
connection.setRequestProperty(“user-agent”, “Mozilla/5.0 (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0”);
if (requestHeader != null && requestHeader.size() > 0) {
for (Entry<String, String> entry : requestHeader.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
connection.connect();
// w2 = new File(“”);
// FileOutputStream fout
// = new FileOutputStream(w2);
input = connection.getInputStream();
// int len = 0;
// byte[] b = new byte[1024];
// while ((len = input.read(b)) != -1) {
// fout.write(b, 0, len);
// }
// fout.flush();
} catch (Exception e) {
} finally {
}
return input;
3.CommonInputStreamResource,将流转换为Resource,上传的时候直接传
org.springframework.core.io.Resource resource = new CommonInputStreamResource(inputStream);
Map fileMap = new HashMap<String, File>();
fileMap.put("file", resource);
public class CommonInputStreamResource extends InputStreamResource {
private int length;
public CommonInputStreamResource(InputStream inputStream) {
super(inputStream);
}
public CommonInputStreamResource(InputStream inputStream, int length) {
super(inputStream);
this.length = length;
}
/**
* 覆写父类方法
* 如果不重写这个方法,并且文件有一定大小,那么服务端会出现异常
* {@code The multi-part request contained parameter data (excluding uploaded files) that exceeded}
*
* @return
*/
@Override
public String getFilename() {
return "temp";
}
/**
* 覆写父类 contentLength 方法
* 因为 {@link org.springframework.core.io.AbstractResource#contentLength()}方法会重新读取一遍文件,
* 而上传文件时,restTemplate 会通过这个方法获取大小。然后当真正需要读取内容的时候,发现已经读完,会报如下错误。
* <code>
* java.lang.IllegalStateException: InputStream has already been read - do not use InputStreamResource if a stream needs to be read multiple times
* at org.springframework.core.io.InputStreamResource.getInputStream(InputStreamResource.java:96)
* </code>
* <p>
* ref:com.amazonaws.services.s3.model.S3ObjectInputStream#available()
*
* @return
*/
@Override
public long contentLength() {
int estimate = length;
return estimate == 0 ? 1 : estimate;
}
通过InputStreamResource下载上传图片相关推荐
- Android OKHttp3的使用和下载/上传图片
一.OKHttp3简介 OKHttp是一个处理网络请求的轻量级开源框架,由移动支付Square公司贡献,用于替代HttpUriConnection和Apache HTTPClient,进行http请求 ...
- Android异步下载网络图片(其一:Handler)
项目中有时候需要获取网络上的图片,并下载下来到手机客户端显示.怎么做呢? 实现思路是: 1:在UI线程中启动一个线程,让这个线程去下载图片. 2:图片完成下载后发送一个消息去通知UI线程 2:UI线程 ...
- php将图片导入,php中图片文件的导入,上传与下载
---------------------------------------------图片的导入-------------------------------------------------- ...
- 基于Hexo和Github搭建博客
文章目录 一.前提 1.1 安装hexo 1.2 初始化hexo 1.3 hexo的一些命令 1.4 关于主题 1.4.1 修改主题 二.搭建github博客 2.1注册一个域名 三.配置ssh ke ...
- 炸了!3年图片都没了!
一直都是用的 Typora+微博免费图床写作,前段时间突然发现图片全都裂了,打开一看都是 403 . 开始我以为图片微博都给我删了,找了一堆平台去翻我的历史文章看图片是不是都在,找了半天发现图片要么不 ...
- destoon7.0火车头免登陆发布接口 destoon模拟人工发布接口 destoon火车头免费采集接口
来源:https://www.destoon.cc/product/view62.html destoon7.0正式版已与2018年4月3日发布,destoon采集专家已与第一时间发布destoon火 ...
- 一起来聆听亚马逊跨境电商新老麦家的心声
在和朋友闲聊时,用朋友的话说,拥有了智赢,等于拥有了最强大的ERP +海量的产品库.智赢ERP好不好用?一起来聆听亚马逊跨境电商新老麦家的心声! 智赢ERP_跨境电商智赢ERP软件<亚马逊用户心 ...
- 服务器端集成环信即使通讯
<?php /** -------------------------------------------------- 环信PHP REST示例代码 --------- ...
- 环信集成服务端封装类-聊天室
环信常用接口封装 <?php class Easemob {private $client_id = '';private $client_secret = "";priva ...
最新文章
- Linux下如何执行Shell脚本
- 【问题解决】移动端rem适配的时候会出现打开页面时先缩小(放大)后恢复到正常页面的问题
- 阿里云网站80端口无法访问
- 一流投资人会关注什么样的区块链初创公司?
- 【VC++技术杂谈005】如何与程控仪器通过GPIB接口进行通信
- 信息学奥赛C++语言:奇数1
- UI实用|素材APP启动图标设计模板
- 生活需要懂点技巧…懂点策略…懂点计谋……【心灵悟语】
- python go rpc_Python RPC 之 gRPC
- html5修改进度条颜色,如何改变HTML5进度条
- c51单片机小车c语言,用51单片机编写的智能小车全程前进的C程序
- 获取每日 联想电脑 开机锁屏壁纸
- CTFHUB刷题 密码口令/默认口令
- bin是什么文件,要如何打开?
- Linux中删除文件,磁盘空间未释放问题追踪
- JavaScript概述和HTML中嵌入JavaScript的三种方式
- xps 9360 8250U 过热死机,CPU散热解决方案,日常温度直降30度 ,从 75 度 到 45度。
- 每日刷题:lightoj-1004 - Monkey Banana Problem
- 数字转换为十六进制数
- matlab dcc,重金感谢(dcc-mvgarch)!
热门文章
- C语言中?:代表什么意思
- 关于Android Toast
- Netty + Web聊天室
- 老男孩51CTO博客博文列表整理版20170620更新
- CreatorPrimer | 飞机大战(一)
- 【信号与系统】Multisim 仿真连续时间系统的时域分析
- linux系统下载及安装(CentOS-7-x86_64-DVD-1810.iso)
- edittext 软键盘上方_Android 软键盘的全面解析,让你不再怕控件被遮盖
- 软件测试工程师和技术支持工程师哪个更有钱途,以后会发展更好?
- 冰河亲自整理的Git命令汇总,悄悄努力,然后惊艳所有人