java传文件流存服务器_使用HttpClient发送文件流到服务器端

packagetest.http;importcom.alibaba.fastjson.JSON;importcom.alibaba.fastjson.JSONArray;importcom.alibaba.fastjson.JSONObject;importorg.apache.http.HttpEntity;importorg.apache.http.HttpResponse;importorg.apache.http.client.methods.HttpPost;importorg.apache.http.entity.ContentType;importorg.apache.http.entity.mime.MultipartEntityBuilder;importorg.apache.http.impl.client.CloseableHttpClient;importorg.apache.http.impl.client.HttpClients;importorg.apache.http.util.EntityUtils;import java.io.*;importjava.net.URL;importjava.nio.charset.Charset;/*** 文件传送

* 发送文件流到服务器端

* 服务器端使用SpringBoot的MultipartFile接收

*

* 适用场景:

* 绝对路径的URL文件,不存储到本地,转换成stream,直接使用HTTPClient传送到SpringBoot

**/

public classTestUpload {public static voidmain(String[] args) {//文件URL,此处取豆瓣上的一个图片

String fileUrl ="https://img1.doubanio.com/view/photo/l/public/p2537149328.webp";try{//提取到文件名

String fileName = fileUrl.substring(fileUrl.lastIndexOf("/")+1);//转换成文件流

InputStream is = newURL(fileUrl).openStream();//接收文件的服务器地址

String uploadURL = "http://localhost:8003/fileupload";//创建HttpClient

CloseableHttpClient httpClient =HttpClients.createDefault();

HttpPost httpPost= newHttpPost(uploadURL);

MultipartEntityBuilder builder=MultipartEntityBuilder.create();/*绑定文件参数,传入文件流和contenttype,此处也可以继续添加其他formdata参数*/builder.addBinaryBody("file",is, ContentType.MULTIPART_FORM_DATA,fileName);

HttpEntity entity=builder.build();

httpPost.setEntity(entity);//执行提交

HttpResponse response =httpClient.execute(httpPost);

HttpEntity responseEntity=response.getEntity();if(responseEntity != null){//将响应的内容转换成字符串

String result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));//此处根据服务器返回的参数转换,这里返回的是JSON格式

JSONObject output =JSON.parseObject(result);

JSONArray body= output.getJSONArray("body");

String resUrl= body.get(0)+"";

System.out.println(resUrl);

}

if(is != null){

is.close();

}

}catch(Exception ex){

ex.printStackTrace();

}

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值