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();
}
}
}