/**
* 发送post请求,dataform方式
* @param url
* @param map
* @param encoding
* @return
*/
public static JsonResult sendPostReqByFormData(String url, Map<String,Object> map, String encoding){
HttpClient client= HttpClients.createDefault();
HttpPost request = new HttpPost(url);
// 装填参数
List<NameValuePair> nameValuePairs = new ArrayList<>();
if (map != null) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
}
try {
request.setEntity(new UrlEncodedFormEntity(nameValuePairs ));
HttpResponse resp = client.execute(request);
HttpEntity entity = resp.getEntity();
if(entity!=null){
String result = EntityUtils.toString(entity,encoding);//解析返回数据
if(result != null && !"".equals(result)){
return new JsonResult(result);
}else{
return new JsonResult("1","获取返回参数信息为空 .");
}
}else{
return new JsonResult("1","请求返回会话实体为空 .");
}
} catch (Exception e) {
logger.info("request post url by form data error {}",e.getMessage());
return new JsonResult("1","请求url"+url+ " 异常");
}
}
/**
* post请求传输json数据
*
* @param url
* @param json
* @param encoding
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static JsonResult sendPostDataByJson(String url, String json, String encoding) throws ClientProtocolException, IOException {
// 创建httpclient对象
HttpClient httpClient = HttpClients.createDefault();
// 创建post方式请求对象
HttpPost httpPost = new HttpPost(url);
// 设置参数到请求对象中
StringEntity stringEntity = new StringEntity(json, ContentType.DEFAULT_TEXT);
stringEntity.setContentEncoding("utf-8");
httpPost.setEntity(stringEntity);
try {
HttpResponse resp = httpClient.execute(httpPost);
HttpEntity entity = resp.getEntity();
if(entity != null){
String result = EntityUtils.toString(entity,encoding);//解析返回数据
if(result != null && !"".equals(result)){
return new JsonResult(result);
}else{
return new JsonResult("1","获取返回参数信息为空 .");
}
}else{
return new JsonResult("1","请求返回会话实体为空 .");
}
} catch (Exception e) {
logger.info("request post url by form data error {}",e.getMessage());
return new JsonResult("1","请求url"+url+ " 异常");
}
}