本文仅已两个不同的接口来模拟两台服务器(两台服务器是同样的代码即可实现)
本文是比较简单的实现【初级版】,能够满足文件的发送,并且能够携带必要的参数
后续会迭代新的版本,比如说多文件传输,参数多样化等
/**
* 模拟发送方
*/
@RequestMapping(value = "/send")
@ResponseBody
public void send() throws IOException {
String requestUrl = "http://127.0.0.1/profile/filetest/rec";
Map<String, String> params = new HashMap<>();
File file = new File("D:\\test\\test.png");
HttpFileUtils.upLoadFilePost(requestUrl, file, params);
}
/**
* 模拟接收方
*/
@RequestMapping(value = "/rec")
@ResponseBody
public String rec(MultipartHttpServletRequest multiRequest){
if (multiRequest == null)
return null;
try {
MultipartFile file = multiRequest.getFile("file");
if (!file.isEmpty()) {
Map<String, String[]> parameterMap = multiRequest.getParameterMap();
//接收参数信息
for(String key: parameterMap.keySet()){
System.err.println(key+":"+parameterMap.get(key));
}
//接收文件
String profilePath = "D:\\test\\1\\rec.png";
File iFile = new File(profilePath);
File iFileParent = iFile.getParentFile();
if (!iFileParent.exists())
iFileParent.mkdirs();
// 转存文件
file.transferTo(iFile);
}
} catch (Exception e1) {
e1.printStackTrace();
logger.info("从Request拉取文件失败");
}
return "success";
}
工具类
/**
* 通用http发送文件方法
*
* @author liguangni
* @Date 2022.03.18
*/
public class HttpFileUtils {
private static final Logger log = LoggerFactory.getLogger(HttpFileUtils.class);
/**
* 通过Http发送单个文件
*
* @param requestUrl 目标接口请求地址
* @param file 发送的文件
* @param params 附加的参数
* @return
* @throws IOException
*/
public static String upLoadFilePost(String requestUrl, File file, Map<String, String> params) throws IOException {
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--", LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
URL uri = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setReadTimeout(5 * 1000);
conn.setDoInput(true);// 允许输入
conn.setDoOutput(true);// 允许输出
conn.setUseCaches(false);
conn.setRequestMethod("POST"); // Post方式
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
// 添加参数
StringBuffer paramsb = new StringBuffer();
for (Map.Entry<String, String> entry : params.entrySet()) {
paramsb.append(PREFIX);
paramsb.append(BOUNDARY);
paramsb.append(LINEND);
paramsb.append("Content-Disposition: form-data;name=\"" + entry.getKey() + "\"");
paramsb.append(LINEND);
paramsb.append(LINEND);
paramsb.append(entry.getValue());
paramsb.append(LINEND);
}
outStream.write(paramsb.toString().getBytes());
// 发送文件数据
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"" + LINEND);
sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes());
InputStream is = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
is.close();
outStream.write(LINEND.getBytes());
// 请求结束标志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
// 得到响应码
int res = conn.getResponseCode();
if (res == 200) {
InputStream in = conn.getInputStream();
InputStreamReader isReader = new InputStreamReader(in);
BufferedReader bufReader = new BufferedReader(isReader);
String line = "";
String data = "";
while ((line = bufReader.readLine()) != null) {
data += line;
}
outStream.close();
conn.disconnect();
return data;
}
outStream.close();
conn.disconnect();
return null;
}
}