public class HttpBase {
private static final String CHARSET = "UTF-8";
private static final String returnType = "application/json";
private static CloseableHttpClient httpClient=null;
private static CloseableHttpResponse response=null;
private static CookieStore cookieStore = null;
private static final Logger LOG = LoggerFactory.getLogger(HttpBase.class);
/**
*
* @param url 请求url
* @param json 请求参数 json类型
* @param methodType 方法模式
* @param contentType 实体正文类型
* @return 返回字符串
*/
protected static String requestReString(String url, JsonObject json, String methodType, String contentType) {
String result = null;
LOG.info("请求url {}",url + ",开始");
try {
httpClient = HttpClients.createDefault();//使用CloseableHttpClient的工厂类HttpClients的方法来创建实例
if(methodType.equals("POST")){
HttpPost httpPost = new HttpPost(url);
if ("application/json".equals(contentType)) {
try {
System.err.println("json----------------------===========---------" + json.toString());
StringEntity requestEntity = new StringEntity(json.toString(), CHARSET);
httpPost.setEntity(requestEntity);
httpPost.setHeader("Content-type",contentType);
url = URLDecoder.decode(url, CHARSET);
System.out.println("http post为:"+ httpPost);
response = httpClient.execute(httpPost);
} catch (Exception e) {
// TODO: handle exception
}
}
else if ("application/octet-stream".equals(contentType)) {
try {
// StringEntity requestEntity = new StringEntity(json.getString("data"), CHARSET);
HttpEntity requestEntity = (HttpEntity)json.get("entity");
httpPost.setEntity(requestEntity);
httpPost.setHeader("Content-type",contentType);
url = URLDecoder.decode(url, CHARSET);
// System.out.println("http post为:"+ json.getString("data"));
System.out.println("http post为:"+ httpPost);
response = httpClient.execute(httpPost);
} catch (Exception e) {
e.printStackTrace();
}
}
else {
List<NameValuePair> params = new ArrayList<NameValuePair>();
if (json != null) {
System.out.println(json.toString());
if (json.size() > 0) {
for (String key : json.keySet()) {
if(json.get(key) == null) {
params.add(new BasicNameValuePair(key, ""));
}else{
params.add(new BasicNameValuePair(key, "" + json.get(key)));
}
}
}
}
StringEntity requestEntity = new UrlEncodedFormEntity(params, CHARSET);
requestEntity.setContentType(contentType);
requestEntity.setContentEncoding("UTF-8");
httpPost.setEntity(requestEntity);
url = URLDecoder.decode(url, CHARSET);
System.out.println(params);
response = httpClient.execute(httpPost);
}
}
else if(methodType.equals("GET")){
if (json != null) {
url += getUrlParam(json);
}
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Accept", contentType);
httpGet.addHeader("Accept-Charset", CHARSET);
//add id58 by zhengxuesheng
httpGet.addHeader(new BasicHeader("Cookie", "id58=c5/njVx+SUAtLtIkBTvTAg=="));
response = httpClient.execute(httpGet);
}
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
result = EntityUtils.toString(responseEntity, CHARSET);
}
} catch (Exception e) {
LOG.error("httpclient调用异常: {}",e.getMessage());
e.printStackTrace();
} finally {
try {
if (response!=null) {
response.close();
}
if (httpClient!=null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
LOG.info("请求url {}",url + ",结束");
return result;
}
/**
* 用于PMS项目
* @param url 请求url
* @param json 请求参数 json类型
* @param methodType 方法模式
* @param contentType 实体正文类型
* @return 返回字符串
*/
@Deprecated
protected static String requestWithHeaderReString(String url, JSONObject headersjson, JsonObject json, String methodType, String contentType) {
String result = null;
LOG.info("请求url {}",url + ",开始");
try {
httpClient = HttpClients.createDefault();
if(methodType.equals("POST")){
HttpPost httpPost = new HttpPost(url);
//Post添加header
if (headersjson != null) {
if (headersjson.size() > 0) {
for (String key : headersjson.keySet()) {
if(headersjson.get(key) == null) {
httpPost.setHeader(key,"");
}else{
httpPost.setHeader(key,headersjson.getString(key));
}
}
}
}
if ("application/json".equals(contentType)) {
try {
System.err.println("jsonjson-----------------------===========---------" + json.toString());
StringEntity requestEntity = new StringEntity(json.toString(), CHARSET);
httpPost.setEntity(requestEntity);
httpPost.setHeader("Content-type",contentType);
url = URLDecoder.decode(url, CHARSET);
System.out.println("http post为:"+ httpPost);
response = httpClient.execute(httpPost);
} catch (Exception e) {
// TODO: handle exception
}
}else{
List<NameValuePair> params = new ArrayList<NameValuePair>();
if (json != null) {
if (json.size() > 0) {
for (String key : json.keySet()) {
if(json.get(key) == null) {
params.add(new BasicNameValuePair(key, ""));
}else{
System.out.println("post入参-key:"+key+"|value:"+json.get(key));
params.add(new BasicNameValuePair(key, "" + json.get(key)));
}
}
}
}
StringEntity requestEntity = new UrlEncodedFormEntity(params, CHARSET);
requestEntity.setContentType(contentType);
requestEntity.setContentEncoding("UTF-8");
httpPost.setEntity(requestEntity);
url = URLDecoder.decode(url, CHARSET);
response = httpClient.execute(httpPost);
}
}
else if(methodType.equals("GET")){
if (json != null) {
url += getUrlParam(json);
}
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Accept", contentType);
httpGet.addHeader("Accept-Charset", CHARSET);
//Get添加header
if (headersjson != null) {
if (headersjson.size() > 0) {
for (String key : headersjson.keySet()) {
if(headersjson.get(key) == null) {
httpGet.addHeader(key,"");
}else{
httpGet.addHeader(key,headersjson.getString(key));
}
}
}
}
response = httpClient.execute(httpGet);
}
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
result = EntityUtils.toString(responseEntity, CHARSET);
}
} catch (Exception e) {
LOG.error("httpclient调用异常: {}",e.getMessage());
e.printStackTrace();
} finally {
try {
if (response!=null) {
response.close();
}
if (httpClient!=null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
LOG.info("请求url {}",url + ",结束");
return result;
}
/**
* 从redis中获取ppu值
* @param url
* @param json
* @param methodType
* @param contentType
* @return
*/
protected static String requestWithredisCookie(String url, JsonObject json, String methodType, String contentType){
return requestWithCookieReString(url, RedisUtil.get("PPU_value"), json, methodType, contentType);
}
/**
* 用于商家后台项目
* @param url 请求url
* @param json 请求参数 json类型
* @param methodType 方法模式
* @param contentType 实体正文类型
* @return 返回字符串
*/
protected static String requestWithCookieReString(String url, String ppu_value, JsonObject json, String methodType, String contentType) {
String result = null;
String domain = ".58.com";
String path = "/";
try {
// 保存PPU进入cookie,并设置domain和path
cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("PPU",ppu_value);
cookie.setSecure(false);
cookie.setDomain(domain);
cookie.setPath(path);
cookieStore.addCookie(cookie);
if(domain != null) cookie.setAttribute("domain", domain);
if(path != null) cookie.setAttribute("path", path);
// new一个带cookie的httplient
httpClient = HttpClients.custom()
.setDefaultCookieStore(cookieStore)
.build();
if(methodType.equals("POST")){
HttpPost httpPost = new HttpPost(url);
// httpPost.setHeader("Content-type",contentType);
httpPost.setHeader("uid",RedisUtil.get("uid_value"));
httpPost.setHeader("referer","https://houserent.m.58.com");
if ("application/json".equals(contentType)) {
try {
System.err.println("json-----------------------===========---------" + json.toString());
StringEntity requestEntity = new StringEntity(json.toString(), CHARSET);
httpPost.setEntity(requestEntity);
httpPost.setHeader("Content-type",contentType);
// httpPost.setHeader("uid",RedisUtil.get("uid_value"));
url = URLDecoder.decode(url, CHARSET);
System.out.println("http post为:"+ httpPost);
response = httpClient.execute(httpPost);
} catch (Exception e) {
// TODO: handle exception
}
}else if("text/plain".equals(contentType)){
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
if (json != null) {
if (json.size() > 0) {
for (String key : json.keySet()) {
if(json.get(key) == null) {
builder.addTextBody(key, "");
}else if("file".equals(key)){
builder.addBinaryBody(key,(File)json.get(key));
}else{
builder.addTextBody(key, "" + json.get(key));
}
}
}
}
httpPost.setEntity(builder.build());
response = httpClient.execute(httpPost);
}else{
List<NameValuePair> params = new ArrayList<NameValuePair>();
if (json != null) {
if (json.size() > 0) {
for (String key : json.keySet()) {
if(json.get(key) == null) {
params.add(new BasicNameValuePair(key, ""));
}else{
params.add(new BasicNameValuePair(key, "" + json.get(key)));
}
}
}
}
StringEntity requestEntity = new UrlEncodedFormEntity(params, CHARSET);
requestEntity.setContentType(contentType);
requestEntity.setContentEncoding("UTF-8");
httpPost.setEntity(requestEntity);
url = URLDecoder.decode(url, CHARSET);
response = httpClient.execute(httpPost);
}
}
else if(methodType.equals("GET")){
if (json != null) {
url += getUrlParam(json);
}
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Accept", contentType);
httpGet.addHeader("Accept-Charset", CHARSET);
httpGet.addHeader("ID58","1234456778");
response = httpClient.execute(httpGet);
}
//拿res返回的cookie
List<Cookie> cookies = cookieStore.getCookies();
for (int i = 0; i < cookies.size(); i++) {
cookieStore.addCookie(cookies.get(i));
System.out.println("Local cookie: " + cookies.get(i));
}
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
result = EntityUtils.toString(responseEntity, CHARSET);
}
} catch (Exception e) {
LOG.error("httpclient调用异常: {}",e.getMessage());
e.printStackTrace();
} finally {
try {
if (response!=null) {
response.close();
}
if (httpClient!=null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
LOG.info("请求url {}",url + ",结束");
return result;
}
/**
* 把header里的参数透传
* @param url 请求url
* @param json 请求参数 json类型
* @param methodType 方法模式
* @param contentType 实体正文类型
* @return 返回字符串
*/
protected static String requestWithCookieMapReString(String url, HashMap<String,String> cookieMap, JsonObject json, String methodType, String contentType) {
String result = null;
String domain = cookieMap.get("domain");
String path = cookieMap.get("path");
try {
// 保存PPU进入cookie,并设置domain和path
cookieStore = new BasicCookieStore();
BasicClientCookie cookie = null;
if(domain.startsWith("anjuke")){
cookie = new BasicClientCookie("ajkAuthTicket",cookieMap.get("ajkAuthTicket"));
}else{
cookie = new BasicClientCookie("PPU",cookieMap.get("PPU"));
}
cookie.setSecure(false);
cookie.setDomain(domain);
cookie.setPath(path);
cookieStore.addCookie(cookie);
if(domain != null) cookie.setAttribute("domain", domain);
if(path != null) cookie.setAttribute("path", path);
// new一个带cookie的httplient
httpClient = HttpClients.custom()
.setDefaultCookieStore(cookieStore)
.build();
if(methodType.equals("POST")){
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("uid",RedisUtil.get("uid_value"));
httpPost.setHeader("referer","https://houserent.m.58.com");
if ("application/json".equals(contentType)) {
try {
System.err.println("json-----------------------===========---------" + json.toString());
StringEntity requestEntity = new StringEntity(json.toString(), CHARSET);
httpPost.setEntity(requestEntity);
httpPost.setHeader("Content-type",contentType);
// httpPost.setHeader("PPU",ppu_value);
url = URLDecoder.decode(url, CHARSET);
System.out.println("http post为:"+ httpPost);
response = httpClient.execute(httpPost);
} catch (Exception e) {
// TODO: handle exception
}
}else if("text/plain".equals(contentType)){
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
if (json != null) {
if (json.size() > 0) {
for (String key : json.keySet()) {
if(json.get(key) == null) {
builder.addTextBody(key, "");
}else if("file".equals(key)){
builder.addBinaryBody(key,(File)json.get(key));
}else{
builder.addTextBody(key, "" + json.get(key));
}
}
}
}
httpPost.setEntity(builder.build());
response = httpClient.execute(httpPost);
}else {
List<NameValuePair> params = new ArrayList<NameValuePair>();
if (json != null) {
if (json.size() > 0) {
for (String key : json.keySet()) {
if(json.get(key) == null) {
params.add(new BasicNameValuePair(key, ""));
}else{
params.add(new BasicNameValuePair(key, "" + json.get(key)));
}
}
}
}
StringEntity requestEntity = new UrlEncodedFormEntity(params, CHARSET);
requestEntity.setContentType(contentType);
requestEntity.setContentEncoding("UTF-8");
httpPost.setEntity(requestEntity);
url = URLDecoder.decode(url, CHARSET);
response = httpClient.execute(httpPost);
}
}
else if(methodType.equals("GET")){
if (json != null) {
url += getUrlParam(json);
}
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Accept", contentType);
httpGet.addHeader("Accept-Charset", CHARSET);
response = httpClient.execute(httpGet);
}
//拿res返回的cookie
List<Cookie> cookies = cookieStore.getCookies();
for (int i = 0; i < cookies.size(); i++) {
cookieStore.addCookie(cookies.get(i));
System.out.println("Local cookie: " + cookies.get(i));
}
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
result = EntityUtils.toString(responseEntity, CHARSET);
}
} catch (Exception e) {
LOG.error("httpclient调用异常: {}",e.getMessage());
e.printStackTrace();
} finally {
try {
if (response!=null) {
response.close();
}
if (httpClient!=null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
LOG.info("请求url {}",url + ",结束");
return result;
}
/**
* 把header和cookie里的参数全都透传过去
* @param url 请求url
* @param json 请求参数 json类型
* @param methodType 方法模式
* @param contentType 实体正文类型
* @return 返回字符串
*/
protected static String requestWithCookieMapAndHeaderMap(String url, HashMap<String,String> cookieMap, HashMap<String,String> userCookieMap, HashMap<String,String> headerMap, JsonObject json, String methodType, String contentType) {
String result = null;
String domain = cookieMap.get("domain");
String path = cookieMap.get("path");
try {
// 保存PPU进入cookie,并设置domain和path
cookieStore = new BasicCookieStore();
BasicClientCookie cookie = null;
if(domain.startsWith("anjuke")){
cookie = new BasicClientCookie("ajkAuthTicket",cookieMap.get("ajkAuthTicket"));
}else{
cookie = new BasicClientCookie("PPU",cookieMap.get("PPU"));
}
cookie.setSecure(false);
cookie.setDomain(domain);
cookie.setPath(path);
cookieStore.addCookie(cookie);
if(domain != null) cookie.setAttribute("domain", domain);
if(path != null) cookie.setAttribute("path", path);
//遍历userHashMap
if(userCookieMap!=null) {
for(String key:userCookieMap.keySet()){
cookieStore.addCookie(new BasicClientCookie(key,userCookieMap.get(key)));
}
}
// 获取cookie
List<Cookie> cookies = cookieStore.getCookies();
for (Cookie c : cookies) {
System.out.println("Local Cookie:" + c);
}
// new一个带cookie的httplient
httpClient = HttpClients.custom()
.setDefaultCookieStore(cookieStore)
.build();
if(methodType.equals("POST")){
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("uid",RedisUtil.get("uid_value"));
//遍历headerMap
if(headerMap!=null){
for(String key:headerMap.keySet()){
httpPost.setHeader(key,headerMap.get(key));
}
}
if ("application/json".equals(contentType)) {
try {
System.err.println("json-----------------------===========---------" + json.toString());
StringEntity requestEntity = new StringEntity(json.toString(), CHARSET);
httpPost.setEntity(requestEntity);
httpPost.setHeader("Content-type",contentType);
// httpPost.setHeader("PPU",ppu_value);
url = URLDecoder.decode(url, CHARSET);
System.out.println("http post为:"+ httpPost);
response = httpClient.execute(httpPost);
} catch (Exception e) {
// TODO: handle exception
}
}else if("text/plain".equals(contentType)){
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
if (json != null) {
if (json.size() > 0) {
for (String key : json.keySet()) {
if(json.get(key) == null) {
builder.addTextBody(key, "");
}else if("file".equals(key)){
builder.addBinaryBody(key,(File)json.get(key));
}else{
builder.addTextBody(key, "" + json.get(key));
}
}
}
}
httpPost.setEntity(builder.build());
response = httpClient.execute(httpPost);
}else {
List<NameValuePair> params = new ArrayList<NameValuePair>();
if (json != null) {
if (json.size() > 0) {
for (String key : json.keySet()) {
if(json.get(key) == null) {
params.add(new BasicNameValuePair(key, ""));
}else{
params.add(new BasicNameValuePair(key, "" + json.get(key)));
}
}
}
}
StringEntity requestEntity = new UrlEncodedFormEntity(params, CHARSET);
requestEntity.setContentType(contentType);
requestEntity.setContentEncoding("UTF-8");
httpPost.setEntity(requestEntity);
url = URLDecoder.decode(url, CHARSET);
response = httpClient.execute(httpPost);
}
}
else if(methodType.equals("GET")){
if (json != null) {
url += getUrlParam(json);
}
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Accept", contentType);
httpGet.addHeader("Accept-Charset", CHARSET);
//遍历headerMap
if(headerMap!=null){
for(String key:headerMap.keySet()){
httpGet.addHeader(key,headerMap.get(key));
}
}
response = httpClient.execute(httpGet);
}
//拿res返回的cookie
// List<Cookie> cookies = cookieStore.getCookies();
// for (int i = 0; i < cookies.size(); i++) {
// cookieStore.addCookie(cookies.get(i));
// System.out.println("Local cookie: " + cookies.get(i));
// }
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
result = EntityUtils.toString(responseEntity, CHARSET);
}
} catch (Exception e) {
LOG.error("httpclient调用异常: {}",e.getMessage());
e.printStackTrace();
} finally {
try {
if (response!=null) {
response.close();
}
if (httpClient!=null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
LOG.info("请求url {}",url + ",结束");
return result;
}
/**
* get参数组装
* @param
* @return
*/
private static String getUrlParam(JsonObject json){
StringBuffer url = new StringBuffer();
if (!json.isEmpty() && json.size()>0) {
url.append("?");
for (String key : json.keySet()) {
try {
url.append(key + "=" + URLEncoder.encode(json.get(key).toString(), CHARSET) + "&");
} catch (Exception e) {
e.printStackTrace();
}
}
url.deleteCharAt(url.length()-1);
}
LOG.info("get请求的参数 {}", url.toString());
return url.toString();
}
}