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下载上传图片相关推荐

  1. Android OKHttp3的使用和下载/上传图片

    一.OKHttp3简介 OKHttp是一个处理网络请求的轻量级开源框架,由移动支付Square公司贡献,用于替代HttpUriConnection和Apache HTTPClient,进行http请求 ...

  2. Android异步下载网络图片(其一:Handler)

    项目中有时候需要获取网络上的图片,并下载下来到手机客户端显示.怎么做呢? 实现思路是: 1:在UI线程中启动一个线程,让这个线程去下载图片. 2:图片完成下载后发送一个消息去通知UI线程 2:UI线程 ...

  3. php将图片导入,php中图片文件的导入,上传与下载

    ---------------------------------------------图片的导入-------------------------------------------------- ...

  4. 基于Hexo和Github搭建博客

    文章目录 一.前提 1.1 安装hexo 1.2 初始化hexo 1.3 hexo的一些命令 1.4 关于主题 1.4.1 修改主题 二.搭建github博客 2.1注册一个域名 三.配置ssh ke ...

  5. 炸了!3年图片都没了!

    一直都是用的 Typora+微博免费图床写作,前段时间突然发现图片全都裂了,打开一看都是 403 . 开始我以为图片微博都给我删了,找了一堆平台去翻我的历史文章看图片是不是都在,找了半天发现图片要么不 ...

  6. destoon7.0火车头免登陆发布接口 destoon模拟人工发布接口 destoon火车头免费采集接口

    来源:https://www.destoon.cc/product/view62.html destoon7.0正式版已与2018年4月3日发布,destoon采集专家已与第一时间发布destoon火 ...

  7. 一起来聆听亚马逊跨境电商新老麦家的心声

    在和朋友闲聊时,用朋友的话说,拥有了智赢,等于拥有了最强大的ERP +海量的产品库.智赢ERP好不好用?一起来聆听亚马逊跨境电商新老麦家的心声! 智赢ERP_跨境电商智赢ERP软件<亚马逊用户心 ...

  8. 服务器端集成环信即使通讯

    <?php /**     --------------------------------------------------     环信PHP REST示例代码     --------- ...

  9. 环信集成服务端封装类-聊天室

    环信常用接口封装 <?php class Easemob {private $client_id = '';private $client_secret = "";priva ...

最新文章

  1. 定时器有几种实现方式?
  2. 通俗说基于Yarn的Map-Reduce过程
  3. 安川g7接线端子图_常用变频器接线端子集锦及接线示意图
  4. 近世代数--整环--高斯整环
  5. Hadoop分布式文件系统--HDFS结构分析
  6. redis类型[string 、list 、 set 、sorted set 、hash]
  7. 单体架构到微服务架构的带来的变化
  8. extmail垃圾邮件存放垃圾邮件箱
  9. 原来嵌套个网页的技术是这样的
  10. Leetcode--全排列(Java)
  11. redis系列:通过队列案例学习list命令 1
  12. 火狐怎么在线升级 火狐浏览器在线升级方法分享
  13. 各操作系统各文件系统支持的最大文件的大小
  14. linux系统上项目部署
  15. 电子工业版了解计算机教案,三年级上册信息技术教案-4.1计算机中的文件和文件夹|电子工业版(宁夏)...
  16. 【大数据】一图了解大数据发展历程
  17. Excel QUARTILE函数计算逻辑
  18. 优秀的流程图是如何制作的?简单的教程讲解
  19. 第几天(c语言实现,两种做法)
  20. 华为方舟编译器开源官网正式上线,并首次开放了框架源码!

热门文章

  1. 【Golang】欲入此Go先看Go的基本语法
  2. 将打开在扩展显示器的界面移动到主显示器中的方法
  3. XenServer Tools
  4. Springboot使用Actuator健康监控以及可视化界面
  5. python甲鱼怎么修改,跟小甲鱼自学python笔记 更新中…
  6. 华为网管地址配置实验
  7. 【Redis】分布式限流与Redis实现限流的四种方式(Redis专栏启动)
  8. how2j离线资源,2018,12月26最新
  9. 帝国理工创新领袖:数据驱动创新的五种模式
  10. 详解awk(一)awk基础知识、选项、程序段解析与实例