post发送文件请求
public static void main(String[] args) throws IOException {
String url = "http://";
Map<String, Object> keyValues = new HashMap<>();
Map<String, String> filePathMap = new HashMap<>();
String paramName = "file";
String filePath = "E:\\dailySoft\\postman\\files\\加密文件.zip";
filePathMap.put(paramName, filePath);
Map<String, Object> headers = new HashMap<>();
headers.put("Authorization","xxxxxxxxxxxxxxxxxxx");
HttpResponse response = postFormData(url, filePathMap, keyValues, headers);
System.out.println(response);
}
public static HttpResponse postFormData(String urlStr, Map<String, String> filePathMap, Map<String, Object> keyValues, Map<String, Object> headers) throws IOException {
HttpResponse response;
HttpURLConnection conn = getHttpURLConnection(urlStr, headers);
String boundary = "MyBoundary" + System.currentTimeMillis();
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) {
if (keyValues != null && !keyValues.isEmpty()) {
for (Map.Entry<String, Object> entry : keyValues.entrySet()) {
writeSimpleFormField(boundary, out, entry);
}
}
if (filePathMap != null && !filePathMap.isEmpty()) {
for (Map.Entry<String, String> filePath : filePathMap.entrySet()) {
writeFile(filePath.getKey(), filePath.getValue(), boundary, out);
}
}
String endStr = BOUNDARY_PREFIX + boundary + BOUNDARY_PREFIX + LINE_END;
out.write(endStr.getBytes());
} catch (Exception e) {
LOGGER.error("HttpUtils.postFormData 请求异常!", e);
response = new HttpResponse(500, e.getMessage());
return response;
}
return getHttpResponse(conn);
}
接受Java发送的post请求方法
@PostMapping(value="testjavasendpost")
public void testjavasendpost(@RequestBody List<Object> params){
System.out.println("dataSource = 1");
}
发送post请求
public static String sendJsonPost(String url, String sendData) throws MyException {
String body = "";
try {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
StringEntity s = new StringEntity(sendData, "UTF-8");
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
httpPost.setEntity(s);
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
httpPost.setHeader("Authorization","Basic Z2F0aGVyOiU4QzhlU0Fmfk5IWGFPamtRbnA=");
HttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
body = EntityUtils.toString(entity, "UTF-8");
}
EntityUtils.consume(entity);
} catch (Exception e) {
throw new MyException("JSON数据发送失败,异常:"+e.getMessage());
}
return body;
}