接口文档
数据请求方式 | post |
---|---|
路由 | 10.0.0.xxx:8080/upload/cert |
输入参数:
字段含义 | 字段名称 | 数据类型 |
---|---|---|
*上传的文件 | file | MultipartFile[] |
*上传用户账号 | userAccount | String |
*证书类别 | category | String |
返回数据:
字段含义 | 字段名称 | 数据类型 |
---|---|---|
返回状态码 0 1 2 3 4 5 | code | String |
提示信息 | message | String |
上传成功文件id | docId | String |
主要方法
//私有公共变量
private final static String BOUNDARY = UUID.randomUUID().toString()
.toLowerCase().replaceAll("-", "");// 边界标识
private final static String PREFIX = "--";// 必须存在
private final static String LINE_END = "\r\n";
//上传方法
public String uploadCertficate(MultipartFile file, String userAccount, String category){
String httpUrl = "http://10.0.0.xxx:8080/upload/cert"; //路由地址
//普通参数信息
Map<String, String> map = new HashMap<String, String>();
map.put("userAccount", userAccount);
map.put("category", category);
//文件参数信息
Map<String, MultipartFile> mapFile = new HashMap<>();
mapFile.put("file", file);
HttpURLConnection connection = null;
InputStream is = null;
OutputStream os = null;
BufferedReader br = null;
String result = null;
try {
URL url = new URL(httpUrl);
// 通过远程url连接对象打开连接
connection = (HttpURLConnection) url.openConnection();
// 设置连接请求方式
connection.setRequestMethod("POST");
// 设置连接主机服务器超时时间:15000毫秒
connection.setConnectTimeout(15000);
// 设置读取主机服务器返回数据超时时间:60000毫秒
connection.setReadTimeout(60000);
// 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
connection.setDoOutput(true);
// 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
connection.setDoInput(true);
// 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
connection.setRequestProperty("Accept", "*/*");
connection.setRequestProperty("Connection", "keep-alive");
connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
connection.setRequestProperty("Charset", "UTF-8");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
// 往服务器端写内容 也就是发起http请求需要带的参数
os = new DataOutputStream(connection.getOutputStream());
// 请求参数部分 这里调用下面的方法!!!
writeParams(map, os);
// 请求上传文件部分 这里调用下面的方法!!!
writeFile(mapFile, os);
// 请求结束标志
String endTarget = PREFIX + BOUNDARY + PREFIX + LINE_END;
os.write(endTarget.getBytes());
os.flush();
// 通过连接对象获取一个输入流,向远程读取
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
// 对输入流对象进行包装:charset根据工作项目组的要求来设置
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuffer sbf = new StringBuffer();
String temp = null;
// 循环遍历一行一行读取数据
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}finally {
// 关闭资源
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != os) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 断开与远程地址url的连接
if (connection != null) {
connection.disconnect();
}
}
System.out.println(result);
return result;
}
传入参数
private static void writeParams(Map<String, String> requestText, OutputStream os) throws Exception {
try{
String msg = "请求参数部分:\n";
if (requestText == null || requestText.isEmpty()) {
msg += "空";
} else {
StringBuilder requestParams = new StringBuilder();
Set<Map.Entry<String, String>> set = requestText.entrySet();
Iterator<Map.Entry<String, String>> it = set.iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
requestParams.append(PREFIX).append(BOUNDARY).append(LINE_END);
requestParams.append("Content-Disposition: form-data; name=\"")
.append(entry.getKey()).append("\"").append(LINE_END);
requestParams.append("Content-Type: text/plain; charset=utf-8")
.append(LINE_END);
requestParams.append("Content-Transfer-Encoding: 8bit").append(
LINE_END);
requestParams.append(LINE_END);// 参数头设置完以后需要两个换行,然后才是参数内容
requestParams.append(entry.getValue());
requestParams.append(LINE_END);
}
os.write(requestParams.toString().getBytes());
os.flush();
msg += requestParams.toString();
}
System.out.println(msg);
}catch(Exception e){
throw new Exception(e);
}
}
传入文件
private static void writeFile(Map<String, MultipartFile> requestFile,
OutputStream os) throws Exception {
InputStream is = null;
try{
String msg = "请求上传文件部分:\n";
if (requestFile == null || requestFile.isEmpty()) {
msg += "空";
} else {
StringBuilder requestParams = new StringBuilder();
Set<Map.Entry<String, MultipartFile>> set = requestFile.entrySet();
Iterator<Map.Entry<String, MultipartFile>> it = set.iterator();
while (it.hasNext()) {
Map.Entry<String, MultipartFile> entry = it.next();
requestParams.append(PREFIX).append(BOUNDARY).append(LINE_END);
requestParams.append("Content-Disposition: form-data; name=\"")
.append(entry.getKey()).append("\"; filename=\"")
.append(entry.getValue().getOriginalFilename()).append("\"")
.append(LINE_END);
requestParams.append("Content-Type:")
.append("multipart/form-data")
.append(LINE_END);
requestParams.append("Content-Transfer-Encoding: 8bit").append(
LINE_END);
requestParams.append(LINE_END);// 参数头设置完以后需要两个换行,然后才是参数内容
os.write(requestParams.toString().getBytes());
is = entry.getValue().getInputStream();
byte[] buffer = new byte[1024*1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
os.write(LINE_END.getBytes());
os.flush();
msg += requestParams.toString();
}
}
System.out.println(msg);
}catch(Exception e){
throw new Exception(e);
}finally{
try{
if(is!=null){
is.close();
}
}catch(Exception e){
throw new Exception(e);
}
}
}
以上方法全部放入UploadUtil.java文件中
方法调用
UploadUtil util = new UploadUtil();
String info = utils.uploadCertficate(multipartFile, userAccount, certType);
System.out.println(info); //输出为json格式,可根据自己需要进行解析处理
返回数据为json格式,可根据自己需要进行解析处理
{
"code": "0",
"docId": "b5bd7cdafaa545c482a2684a194cae93",
"message": "文件上传成功"
}
参考了很多博主的代码,针对我的具体情况做了一些更改,最终实现了想要的效果。希望可以帮到同为初学者的大家。
如果传输文件类型为File的话,可以参考以下链接:
https://blog.csdn.net/vily_luky/article/details/88039536
https://blog.csdn.net/u010957645/article/details/83274795
网络编程这块我没有深入地了解过,如果有更好、更简洁的实现方法,望不吝赐教。