发送 上传文件的 post 请求

文章目录
  1. 1. 代码
    1. 1.1. 工具类
    2. 1.2. 通过 url 上传
  2. 2. 调用
  3. 3. 总结

最近公司对接第三方的接口,对方的接口有一个参数需要上传一个multipart文件,用常规的 post 的请求一直失败

代码

工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
package com.eryansky.modules.aiqiangua.utils;

import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

/**
* HTTP请求对象
*
* @author YYmmiinngg
*/
public class HttpUtil {
private static Logger log = LoggerFactory.getLogger(HttpUtil.class);

/**
* 常规 get
* @param requestUrl
* @param cookie
* @return
*/
public static JSONObject sendGet(String requestUrl, String cookie) {
log.info("url:" + requestUrl);
String res = "";
JSONObject object = null;
StringBuffer buffer = new StringBuffer();
try {
URL url = new URL(requestUrl);
HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
urlCon.setRequestProperty("cookie", cookie); // 设置cookie
log.info(JSON.toJSONString(urlCon.getResponseCode()));
if (200 == urlCon.getResponseCode()) {
InputStream is = urlCon.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
String str = null;
while ((str = br.readLine()) != null) {
buffer.append(str);
}
br.close();
isr.close();
is.close();
res = buffer.toString();
JSONObject parse = new JSONObject();
object = (JSONObject) parse.parse(res);
} else {
throw new Exception("连接失败");
}
} catch (Exception e) {
e.printStackTrace();
}
return object;
}

/**
* 常规 post
* @param strURL
* @param jsonStr
* @param cookie
* @return
*/
public static JSONObject sendPost(String strURL, String jsonStr, String cookie) {
log.info("url:" + strURL);
OutputStreamWriter out = null;
InputStream is = null;
try {
URL url = new URL(strURL);// 创建连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod("POST"); // 设置请求方式
connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
connection.setRequestProperty("cookie", cookie); // 设置cookie
connection.connect();
out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
out.append(jsonStr);
out.flush();
out.close();

// 读取响应
is = connection.getInputStream();
int length = (int) connection.getContentLength();// 获取长度
if (length != -1) {
byte[] data = new byte[length];
byte[] temp = new byte[512];
int readLen = 0;
int destPos = 0;
while ((readLen = is.read(temp)) > 0) {
System.arraycopy(temp, 0, data, destPos, readLen);
destPos += readLen;
}
String result = new String(data, "UTF-8"); // utf-8编码
return JSON.parseObject(result);
}

} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}


/**
* post请求 不带file
* 参数使用
* JSONObject jp = new JSONObject();
* String param = jp.toJSONString()
*/
public static JSONObject sendPostRequest(String fileOCRUrl, HashMap<String, Object> map, String cookie) {
DataOutputStream out = null;
DataInputStream in = null;
final String newLine = "\r\n";
final String prefix = "--";
JSONObject json = null;
try {
URL url = new URL(fileOCRUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

String BOUNDARY = "-------KingKe0520a";
conn.setRequestMethod("POST");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
conn.setRequestProperty("cookie", cookie); // 设置cookie
out = new DataOutputStream(conn.getOutputStream());

StringBuilder sb = new StringBuilder();
int k = 1;
for (String key : map.keySet()) {
if (k != 1) {
sb.append(newLine);
}
sb.append(prefix);
sb.append(BOUNDARY);
sb.append(newLine);
sb.append("Content-Disposition: form-data;name=" + key + "");
sb.append(newLine);
sb.append(newLine);
sb.append(map.get(key));
out.write(sb.toString().getBytes());
sb.delete(0, sb.length());
k++;
}

byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(end_data);
out.flush();

// 定义BufferedReader输入流来读取URL的响应
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
StringBuffer resultStr = new StringBuffer();
while ((line = reader.readLine()) != null) {
resultStr.append(line);
}
json = (JSONObject) JSONObject.parse(resultStr.toString());

} catch (Exception e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return json;
}

/**
* post请求 带file,map是其余参数
*/

public static JSONObject sendPostWithFile(String fileOCRUrl, MultipartFile file, String fileKey, HashMap<String, Object> map, String cookie) {
DataOutputStream out = null;
DataInputStream in = null;
final String newLine = "\r\n";
final String prefix = "--";
JSONObject json = null;
try {
URL url = new URL(fileOCRUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

String BOUNDARY = "-------KingKe0520a";
conn.setRequestMethod("POST");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
conn.setRequestProperty("cookie", cookie); // 设置cookie
out = new DataOutputStream(conn.getOutputStream());

// 添加参数file
// File file = new File(filePath);
StringBuilder sb1 = new StringBuilder();
sb1.append(prefix);
sb1.append(BOUNDARY);
sb1.append(newLine);
sb1.append("Content-Disposition: form-data;name=\""+fileKey+"\";filename=\"" + file.getName() + "\"" + newLine);
sb1.append("Content-Type:application/octet-stream");
sb1.append(newLine);
sb1.append(newLine);
out.write(sb1.toString().getBytes());
// in = new DataInputStream(new FileInputStream(file));
in = new DataInputStream(file.getInputStream());
byte[] bufferOut = new byte[1024];
int bytes = 0;
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
out.write(newLine.getBytes());

StringBuilder sb = new StringBuilder();
int k = 1;
for (String key : map.keySet()) {
if (k != 1) {
sb.append(newLine);
}
sb.append(prefix);
sb.append(BOUNDARY);
sb.append(newLine);
sb.append("Content-Disposition: form-data;name=" + key + "");
sb.append(newLine);
sb.append(newLine);
sb.append(map.get(key));
out.write(sb.toString().getBytes());
sb.delete(0, sb.length());
k++;
}

// 添加参数sysName
/*StringBuilder sb = new StringBuilder();
sb.append(prefix);
sb.append(BOUNDARY);
sb.append(newLine);
sb.append("Content-Disposition: form-data;name=\"sysName\"");
sb.append(newLine);
sb.append(newLine);
sb.append("test");
out.write(sb.toString().getBytes());*/

// 添加参数returnImage
/*StringBuilder sb2 = new StringBuilder();
sb2.append(newLine);
sb2.append(prefix);
sb2.append(BOUNDARY);
sb2.append(newLine);
sb2.append("Content-Disposition: form-data;name=\"returnImage\"");
sb2.append(newLine);
sb2.append(newLine);
sb2.append("false");
out.write(sb2.toString().getBytes());*/

byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(end_data);
out.flush();

// 定义BufferedReader输入流来读取URL的响应
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
StringBuffer resultStr = new StringBuffer();
while ((line = reader.readLine()) != null) {
resultStr.append(line);
}
json = (JSONObject) JSONObject.parse(resultStr.toString());

} catch (Exception e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return json;
}
}

通过 url 上传

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package com.eryansky.modules.aiqiangua.utils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.http.entity.ContentType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileUtil {
/**
* url转变为 MultipartFile对象
* @param url
* @param fileName
* @return
* @throws Exception
*/
public static MultipartFile createFileItem(String url, String fileName) throws Exception{
FileItem item = null;
try {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setReadTimeout(30000);
conn.setConnectTimeout(30000);
//设置应用程序要从网络连接读取数据
conn.setDoInput(true);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream is = conn.getInputStream();

FileItemFactory factory = new DiskFileItemFactory(16, null);
String textFieldName = fileName;
item = factory.createItem(textFieldName, ContentType.APPLICATION_OCTET_STREAM.toString(), false, fileName);
OutputStream os = item.getOutputStream();

int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
is.close();
}
} catch (IOException e) {
throw new RuntimeException("文件下载失败", e);
}

return new CommonsMultipartFile(item);
}

/**
* MultipartFile 转 File
*
* @param file
* @throws Exception
*/
public static File multipartFileToFile(MultipartFile file) throws Exception {

File toFile = null;
if (file.equals("") || file.getSize() <= 0) {
file = null;
} else {
InputStream ins = null;
ins = file.getInputStream();
toFile = new File(file.getOriginalFilename());
inputStreamToFile(ins, toFile);
ins.close();
}
return toFile;
}

//获取流文件
public static void inputStreamToFile(InputStream ins, File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 删除本地临时文件
* @param file
*/
public static void delteTempFile(File file) {
if (file != null) {
File del = new File(file.toURI());
del.delete();
}
}
}

调用

直接调用 key 是上传文件的 key , cookie 是对方接口访问授权,可以根据自己的业务逻辑修改

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* 测试
*
* @param request
*/
@ApiOperation("测试")
@RequestMapping(value = {"test"}, method = RequestMethod.POST)
@ResponseBody
public Result test(HttpServletRequest request, Integer type, @RequestParam(value = "file", required = false) MultipartFile file) {
try {
//url 的调用
String cookie = "第三方授权返回的cookie";
HashMap<String, Object> params = new HashMap<>();
if (type != null) {
file = FileUtil.createFileItem("远程文件地址", "文件名称例如123.png");
}
JSONObject result = HttpRequester.sendPostWithFile("接口地址", file, "key", params, cookie);
return Result.success().setData(result);
}catch (Exception e){
logger.error(e.getMessage(), e);
return Result.error().setMsg(e.getMessage());
}
}

总结

参考文章

出现问题不可怕,关键是要定位到问题的关键,才能快速解决问题!

评论