项目中需要上传一系统的参数和车辆出入场图片。
/**
* @param serverUrl 请求的URL
* @param paramMap 要发送的参数
* @param filePath 图片路径
* @return
*/
public static String sendFile(String serverUrl, Map<String, Object> paramMap, String filePath) {
String strResponse = null;
String boundary = "----------------------7dc2eeba03c6";
try {
URL url = new URL(serverUrl);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
logger.info("=============== 开始设置SSL");
setSSLSocketFactory(connection, false, false, null, null);
logger.info("=============== SSL设置完成");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Charset", "UTF-8");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
//传输内容
StringBuffer contentBody = new StringBuffer("--" + boundary);
OutputStream out = connection.getOutputStream();
//1.处理文字参数
if(paramMap != null){
for(String key : paramMap.keySet()){
contentBody.append("\r\n")
.append("Content-disposition: form-data;name=\"")
.append(key + "\"")
.append("\r\n")
.append("\r\n")
.append(paramMap.get(key))
.append("\r\n")
.append("--")
.append(boundary);
}
}
logger.info("boundaryMessage1:" + contentBody.toString());
out.write(contentBody.toString().getBytes("utf-8"));
//2处理文件上传
StringBuffer fileContentBody = new StringBuffer("\r\n")
.append("Content-disposition:form-data; name=\"image\"; filename=\"ARTC0" + System.currentTimeMillis() + ".jpg\"\r\n")
.append("Content-Type:image/jpg\r\nContent-Transfer-Encoding: binary\r\n\r\n");
logger.info("boundaryMessage2:" + fileContentBody.toString());
out.write(fileContentBody.toString().getBytes("utf-8"));
//开始真正向服务器写文件
File file = new File(filePath);
if(!file.exists() || !file.isFile()){
throw new IOException("对应文件不存在");
}
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
//3.结尾部分
byte[] foot = ("\r\n--" + boundary + "--\r\n").getBytes("UTF-8");
out.write(foot);
out.flush();
out.close();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
if(null == strResponse){
strResponse = buffer.toString();
}
} catch (Exception e) {
logger.error("====================发送POST请求出现异常" + e.getMessage(),e);
throw new IOException("数据读取异常");
} finally {
if(reader != null){
reader.close();
}
}
logger.info("=====================调用图片上传接口返回内容为:" + strResponse);
return strResponse;
} catch (Exception e) {
logger.error("=====================调用图片上传接口出错:" + e.getMessage());
e.printStackTrace();
}
return strResponse;
}
注意图片的name和filename要设置,各个换行要严格控制。