use of org.apache.hc.core5.http.message.BasicNameValuePair in project weicoder by wdcode.
the class HttpUpload method upload.
/**
* 上传文件
*
* @param url post提交地址
* @param data 提交参数
* @param files 上传文件
* @return 返回结果
*/
public static String upload(String url, Map<String, Object> data, File... files) {
// 如果文件为空
if (U.E.isEmpty(url) || U.E.isEmpty(files))
return StringConstants.EMPTY;
// 声明HttpPost
HttpPost post = null;
try {
// 获得HttpPost
post = new HttpPost(url);
// 参数
if (U.E.isNotEmpty(data)) {
// 声明参数列表
List<NameValuePair> list = Lists.newList(data.size());
// 设置参数
data.forEach((k, v) -> list.add(new BasicNameValuePair(k, W.C.toString(v))));
// 设置参数与 编码格式
post.setEntity(new UrlEncodedFormEntity(list));
}
// 多提交实体构造器
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
// 设置浏览器上传
builder.setMode(HttpMultipartMode.EXTENDED);
// 添加上传文件
for (File file : files) builder.addBinaryBody(file.getName(), file);
// 设置提交文件参数
post.setEntity(builder.build());
// 返回结果
return IOUtil.readString(HttpClient.CLIENT.execute(post).getEntity().getContent());
} catch (Exception e) {
LOG.error(e);
} finally {
// 销毁post
if (post != null) {
post.abort();
}
}
return StringConstants.EMPTY;
}
use of org.apache.hc.core5.http.message.BasicNameValuePair in project weicoder by wdcode.
the class HttpClient5 method post.
@Override
public String post(String url, Map<String, Object> data, Map<String, Object> header) {
try {
// 获得HttpPost
HttpPost post = new HttpPost(url);
// 如果参数列表为空 data为空map
if (U.E.isNotEmpty(data)) {
// 声明参数列表
List<NameValuePair> list = Lists.newList(data.size());
// 设置参数
data.forEach((k, v) -> list.add(new BasicNameValuePair(k, W.C.toString(v))));
// 设置参数与 编码格式
post.setEntity(new UrlEncodedFormEntity(list));
}
// 添加http头
if (U.E.isNotEmpty(header))
header.forEach((k, v) -> post.addHeader(k, v));
Logs.debug("HttpClient post url={} data={} header={}", url, data, header);
// 返回结果
return U.I.readString(CLIENT.execute(post).getEntity().getContent());
} catch (Exception e) {
Logs.error(e);
}
return C.S.EMPTY;
}
Aggregations