java向客户端发送json java http发送文件
转载
1.POM依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.2</version>
</dependency>
2.发送文件请求工具类
package com.example.demo.util;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class HttpUtil {
public static String sendFileReq(String url, MultipartEntityBuilder multipartEntityBuilder, String encoding) throws IOException {
String body = "";
//创建httpclient对象
CloseableHttpClient client = HttpClients.createDefault();
//创建post方式请求对象
HttpPost httpPost = new HttpPost (url);
//设置请求参数
HttpEntity httpEntity = multipartEntityBuilder.build();
httpPost.setEntity(httpEntity);
//执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response = client.execute(httpPost);
//获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, encoding);
}
EntityUtils.consume(entity);
//释放链接
response.close();
return body;
}
public static void main(String[] args) {
String url = "http://localhost:8080/receivePostReq";
File attach_file = new File("D:/1/a.png");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setContentType(ContentType.MULTIPART_FORM_DATA);
builder.addBinaryBody("attach_file",attach_file);
// ContentType contentType = ContentType.create("text/plain","utf-8");
ContentType contentType = ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), StandardCharsets.UTF_8);
StringBody stringBody = new StringBody("发送文件",contentType);
builder.addPart("userName",stringBody);
try {
String result1 = sendFileReq (url, builder, "utf-8");
System.out.println (result1);
} catch (Exception e) {
e.printStackTrace ( );
}
}
}
3.验证测试接口
package com.example.demo.controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Calendar;
@RestController
public class DemoController {
@PostMapping("/receivePostReq")
public String receivePostReq(
@RequestParam(value = "userName") String userName,
@RequestParam(value = "attach_file") MultipartFile[] attach_file,
HttpServletRequest request
){
System.out.println("userName="+userName);
//这里file可以接受前台的文件,可以是一个,也可以是多个,这正是MultipartFile强大的地方。
String filePath = "D:\\1";
String fileName[]=new String[attach_file.length];
if (attach_file != null && attach_file.length > 0) {
//判断使用有文件上传
for (int i = 0; i < attach_file.length; i++) {
//循环上传(多文件上传)
try {
Calendar cale = null;
cale = Calendar.getInstance();
int year = cale.get(Calendar.YEAR); int month = cale.get(Calendar.MONTH) + 1;
int day = cale.get(Calendar.DATE);
//给图片重命名加上日期前缀
// filePath= request.getSession().getServletContext().getRealPath("/") ;
//获取服务器img文件夹地址(这里指的是local:8080/项目名/img)
fileName[i]= "/img/" + year + ""+ month + "" + day + "_" + attach_file[i].getOriginalFilename();
//重命名图片。
String type = fileName[i].substring(fileName[i].lastIndexOf(".")+1, fileName[i].length());
//截取文件后缀判断是否是一张图片
if((type.equals("png"))||(type.equals("jpg"))||(type.equals("jpeg"))){
int length = attach_file[i].getBytes().length;
if (!((length / 1000) > 5120)) {
//判断图片地址
System.out.println("图片"+i+"="+fileName[i]);
//将图片输出到制定的文件夹目录中
attach_file[i].transferTo(new File(filePath,fileName[i]));
}else{
System.out.println("图片过大");
}
}else{
System.out.println("只能上传图片啊亲!");
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("上传失败");
}
}
} else {
System.out.println("请选择文件");
}
return "请求成功";
}
}
4.总结
本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。