qa-prevention-gwj/src/main/java/com/zcloud/util/HttpClientService.java

468 lines
17 KiB
Java
Raw Normal View History

2023-11-07 09:32:12 +08:00
package com.zcloud.util;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zcloud.entity.PageData;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
/**
* HttpClientGETPOST
* @Author libin
* @CreateDate 2018.5.28 16:56
*/
public class HttpClientService {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientService.class);
/**
*
*/
private static final int SUCCESS_CODE = 200;
/**
* GET
* @param url url
* @param nameValuePairList
* @return JSON
* @throws Exception
*/
public static Object sendGet(String url, List<NameValuePair> nameValuePairList) throws Exception{
JSONObject jsonObject = null;
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try{
/**
* HttpClient
*/
client = HttpClients.createDefault();
/**
* URIBuilder
*/
URIBuilder uriBuilder = new URIBuilder(url);
/**
*
*/
uriBuilder.addParameters(nameValuePairList);
/**
* HttpGet
*/
HttpGet httpGet = new HttpGet(uriBuilder.build());
/**
*
*/
httpGet.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));
/**
*
*/
httpGet.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));
/**
*
*/
response = client.execute(httpGet);
/**
*
*/
int statusCode = response.getStatusLine().getStatusCode();
if (SUCCESS_CODE == statusCode){
/**
*
*/
HttpEntity entity = response.getEntity();
/**
* EntityUitls
*/
String result = EntityUtils.toString(entity,"UTF-8");
/**
* json,json
*/
try{
jsonObject = JSONObject.parseObject(result);
return jsonObject;
}catch (Exception e){
return result;
}
}else{
LOGGER.error("HttpClientService-line: {}, errorMsg{}", 97, "GET请求失败");
}
}catch (Exception e){
LOGGER.error("HttpClientService-line: {}, Exception: {}", 100, e);
} finally {
response.close();
client.close();
}
return null;
}
/**
* POST
* @param url
* @param nameValuePairList
* @return JSON
* @throws Exception
*/
public static Object sendPost(String url, List<NameValuePair> nameValuePairList) throws Exception{
JSONObject jsonObject = null;
HttpClient client = new SSLClient();
HttpResponse response = null;
try{
/**
* httpclient
*/
client = HttpClients.createDefault();
/**
* post
*/
HttpPost post = new HttpPost(url);
/**
* Entity
*/
StringEntity entity = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");
/**
*
*/
post.setEntity(entity);
/**
*
*/
post.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded;"));
/**
*
*/
post.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));
/**
* 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;
}
/**
* POST
* @param url
* @param headerMap
* @param bodyMap
* @return JSON
* @throws Exception
*/
public static Object sendPostJson(String url, Map<String, Object> headerMap, Map<String, Object> bodyMap) throws Exception{
JSONObject jsonObject = null;
HttpClient client = new SSLClient();
HttpResponse response = null;
try{
/**
* httpclient
*/
client = HttpClients.createDefault();
/**
* post
*/
HttpPost post = new HttpPost(url);
for (Map.Entry<String, Object> entry : headerMap.entrySet()) {
post.setHeader(entry.getKey(), entry.getValue().toString());
}
/**
* Entity
*/
StringEntity entity = new StringEntity(JSONObject.toJSONString(bodyMap), ContentType.create("application/json", "utf-8"));
/**
*
*/
post.setEntity(entity);
/**
* 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;
}
/**
* POSTAccept
* @param url
* @param nameValuePairList
* @return JSON
* @throws Exception
*/
public static Object sendPostNoAccept(String url, List<NameValuePair> nameValuePairList) throws Exception{
JSONObject jsonObject = null;
HttpClient client = new SSLClient();
HttpResponse response = null;
try{
/**
* httpclient
*/
client = HttpClients.createDefault();
/**
* post
*/
HttpPost post = new HttpPost(url);
/**
* Entity
*/
StringEntity entity = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");
/**
*
*/
post.setEntity(entity);
/**
*
*/
post.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded;"));
/**
*
*/
//post.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));
/**
* 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;
}
/**
* {}
* @param params
* @param values
* @return
*/
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;
}
public static void main(String[] args) throws Exception{
// String url = "http://192.168.210.7:8091/api/internal/sign";
// Map<String, Object> map = new HashMap<String, Object>();
// map.put("userName", "9999");
// map.put("password", "123456");
// Object result2 = HttpClientService.sendPostJson(url, new HashMap<String, Object>(), map);
// System.out.println("POST返回信息" + result2);
String url = "http://192.168.210.7:8091/api/base/depts";
Map<String, Object> headerMap = new HashMap<String, Object>();
headerMap.put("appId", "app01");
headerMap.put("v", "1.0");
headerMap.put("random", "123456");
headerMap.put("timestamp", "1660639939220");
headerMap.put("sign", "396AADDF69F55EC719E3985C87B23C4C");
Map<String, Object> bodyMap = new HashMap<String, Object>();
bodyMap.put("pageIndex", 1);
bodyMap.put("pageSize", 100);
Object result2 = HttpClientService.sendPostJson(url, headerMap, bodyMap);
System.out.println("POST返回信息" + result2);
}
public static Map doPost(String url, PageData pd) {
JSONObject jsonObject = null;
HttpResponse response = null;
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
Map<Object, Object> map = (Map)pd;
System.out.print("参数:{");
for(Map.Entry<Object, Object> entry : map.entrySet()){
System.out.print(entry.getKey().toString() + ":" + entry.getValue().toString() + ",");
nameValuePairList.add(new BasicNameValuePair(entry.getKey().toString(), entry.getValue().toString()));
}
System.out.println("}");
try{
/**
* httpclient
*/
HttpClient client = HttpClients.createDefault();
/**
* post
*/
HttpPost post = new HttpPost(url);
/**
*
*/
post.setHeader(new BasicHeader("Source", "zcloud"));
/**
*
*/
post.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded;"));
/**
* Entity
*/
StringEntity entity = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");
/**
*
*/
post.setEntity(entity);
/**
* post
*/
response = client.execute(post);
/**
*
*/
int statusCode = response.getStatusLine().getStatusCode();
// System.out.println("statusCode:" + statusCode);
if (SUCCESS_CODE == statusCode){
/**
* EntityUitls
*/
String result = EntityUtils.toString(response.getEntity(),"UTF-8");
// System.out.println(result);
/**
* json,json
*/
try{
jsonObject = JSONObject.parseObject(result);
Map<String, Object> maps = new HashMap<String, Object>();
maps = parseJSON2Map(jsonObject);
return maps;
}catch (Exception e){
e.printStackTrace();
return null;
}
}else{
LOGGER.error("HttpClientUtil-line: {}, errorMsg{}", 146, "POST请求失败");
}
} catch (Exception e){
LOGGER.error("HttpClientUtil-line: {}, Exception{}", 149, e);
} finally {
/* response.close();
client.close();*/
}
return null;
}
public static Map<String, Object> parseJSON2Map(JSONObject json) {
Map<String, Object> map = new HashMap<String, Object>();
// 最外层解析
for (Object k : json.keySet()) {
Object v = json.get(k);
// 如果内层还是json数组的话继续解析
if (v instanceof JSONArray) {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Iterator<Object> it = ((JSONArray) v).iterator();
while (it.hasNext()) {
JSONObject json2 = (JSONObject) it.next();
list.add(parseJSON2Map(json2));
}
map.put(k.toString(), list);
} else if (v instanceof JSONObject) {
// 如果内层是json对象的话继续解析
map.put(k.toString(), parseJSON2Map((JSONObject) v));
} else {
// 如果内层是普通对象的话直接放入map中
map.put(k.toString(), v);
}
}
return map;
}
}