httpClien调用URL 并传递参数获取返回值方法:
package com.delta.whLab.httpClient;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class LogHttpClient {
private static final int SUCCESS_CODE = 200;
/**
* 发送POST请求
*
* @param url
* @param nameValuePairList
* @return JSON或者字符串
* @throws Exception
*/
public static Object sendPost(String url, List<NameValuePair> nameValuePairList) throws Exception {
JSONObject jsonObject = null;
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try {
/**
* 创建一个httpclient对象
*/
client = HttpClients.createDefault();
/**
* 创建一个post对象
*/
HttpPost post = new HttpPost(url);
/**
* 包装成一个Entity对象
*/
//把传入的List转换为JSONObject
String jsonObjectTemp = JSON.toJSONString(nameValuePairList.get(0));
System.out.println("jsonObjectTemp is:"+jsonObjectTemp);
//StringEntity entity = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");
StringEntity entity = new StringEntity(jsonObjectTemp);
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
System.out.println("entity is:"+entity.toString());
/**
* 设置请求的内容
*/
post.setEntity(entity);
/**
* 设置请求的报文头部的编码
*/
post.setHeader(new BasicHeader("Content-Type", "application/json;charset=UTF-8"));
/**
* 设置请求的报文头部的编码
*/
post.setHeader(new BasicHeader("Accept", "*/*"));
//post.setHeader("token","cY+m7hOS9syYmJum7hOS9s0BkZWx0YXd3LmNvbWM=5");
/**
* 执行post请求
*/
response = client.execute(post);
/**
* 获取响应码
*/
int statusCode = response.getStatusLine().getStatusCode();
if (SUCCESS_CODE == statusCode) {
/**
* 通过EntityUitls获取返回内容
*/
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
/**
* 转换成json,根据合法性返回json或者字符串
*/
try {
jsonObject = JSONObject.parseObject(result);
return jsonObject;
} catch (Exception e) {
return result;
}
} else {
// LOGGER.error("HttpClientService-line: {}, errorMsg:{}", 146, "POST请求失败!");
}
} catch (Exception e) {
// LOGGER.error("HttpClientService-line: {}, Exception:{}", 149, e);
} finally {
response.close();
client.close();
}
return null;
}
public static Object sendPost2(String url, List<Map<String, String>> nameValuePairList) throws Exception {
JSONObject jsonObject = null;
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try {
/**
* 创建一个httpclient对象
*/
client = HttpClients.createDefault();
/**
* 创建一个post对象
*/
HttpPost post = new HttpPost(url);
/**
* 包装成一个Entity对象
*/
//把传入的List转换为JSONObject
String jsonObjectTemp = JSON.toJSONString(nameValuePairList.get(0));
//System.out.println("jsonObjectTemp is:"+jsonObjectTemp);
//StringEntity entity = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");
StringEntity entity = new StringEntity(jsonObjectTemp);
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
//System.out.println("entity is:"+entity.toString());
/**
* 设置请求的内容
*/
post.setEntity(entity);
/**
* 设置请求的报文头部的编码
*/
post.setHeader(new BasicHeader("Content-Type", "application/json;charset=UTF-8"));
/**
* 设置请求的报文头部的编码
*/
post.setHeader(new BasicHeader("Accept", "*/*"));
//post.setHeader("token","cY+m7hOS9syYmJum7hOS9s0BkZWx0YXd3LmNvbWM=5");
//HttpPost method = new HttpPost(url);
try {
if(null != jsonObjectTemp) {
post.addHeader("Content-Type", "application/json;charset=UTF-8");
post.addHeader("Accept", "application/json");
post.setEntity(new StringEntity(jsonObjectTemp.toString(),Charset.forName("UTF-8")));
}
} catch (Exception e) {
// TODO: handle exception
}
/**
* 执行post请求
*/
response = client.execute(post);
/**
* 获取响应码
*/
int statusCode = response.getStatusLine().getStatusCode();
if (SUCCESS_CODE == statusCode) {
/**
* 通过EntityUitls获取返回内容
*/
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
/**
* 转换成json,根据合法性返回json或者字符串
*/
try {
jsonObject = JSONObject.parseObject(result);
return jsonObject;
} catch (Exception e) {
return result;
}
} else {
// LOGGER.error("HttpClientService-line: {}, errorMsg:{}", 146, "POST请求失败!");
}
} catch (Exception e) {
// LOGGER.error("HttpClientService-line: {}, Exception:{}", 149, e);
} finally {
response.close();
client.close();
}
return null;
}
public static List<NameValuePair> getParams(Object[] params, Object[] values) {
/**
* 校验参数合法性
*/
boolean flag = params.length > 0 && values.length > 0 && params.length == values.length;
if (flag) {
List<NameValuePair> nameValuePairList = new ArrayList<>();
for (int i = 0; i < params.length; i++) {
nameValuePairList.add(new BasicNameValuePair(params[i].toString(), values[i].toString()));
}
return nameValuePairList;
} else {
// LOGGER.error("HttpClientService-line: {}, errorMsg:{}", 197,
// "请求参数为空且参数长度不一致");
}
return null;
}
}