public static String postParams(String url, Map<String, String> params, List<File> listFile) {
// 获取连接客户端工具
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
// 创建POST请求对象
HttpPost httpPost = new HttpPost(url);
// 设置参数
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
for (Iterator iter = params.keySet().iterator(); iter.hasNext(); ) {
String name = (String) iter.next();
String value = String.valueOf(params.get(name));
multipartEntityBuilder.addTextBody(name, value, ContentType.TEXT_PLAIN.withCharset("UTF-8"));
}
for (File file : listFile) {
multipartEntityBuilder.addPart("fileStream", new FileBody(file));
}
HttpEntity sentity = multipartEntityBuilder.build();
httpPost.setEntity(sentity);
response = httpClient.execute(httpPost);
// 获得响应的实体对象
HttpEntity entity = response.getEntity();
// 使用Apache提供的工具类进行转换成字符串
String entityStr = EntityUtils.toString(entity, "UTF-8");
httpPost.releaseConnection();
return entityStr;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 释放连接
if (null != response) {
try {
response.close();
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
post请求 http
猜你喜欢
转载自blog.csdn.net/qq_38618691/article/details/114582291
今日推荐
周排行