<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.10</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5</version>
</dependency>
package com.woniu.tools;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
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.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import java.io.IOException;
import java.lang.reflect.Type;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
public class ApiClient {
private static final int MaxConnectTimeout = 30000;
private static String apiServer = null;
private static PoolingHttpClientConnectionManager connectionManager;
private static RequestConfig requestConfig;
static {
// 设置连接池
connectionManager = new PoolingHttpClientConnectionManager();
// 设置连接池大小
connectionManager.setMaxTotal(200);
connectionManager.setDefaultMaxPerRoute(100);
RequestConfig.Builder builder = RequestConfig.custom();
// 设置连接超时
builder.setConnectTimeout(MaxConnectTimeout);
// 设置读取超时
builder.setSocketTimeout(MaxConnectTimeout);
// 设置从连接池获取连接实例的超时
builder.setConnectionRequestTimeout(MaxConnectTimeout);
// 在提交请求之前 测试连接是否可用
requestConfig = builder.build();
}
public static <T> T call(String path, Type resultType) {
return call(path, new HashMap<>(0), resultType);
}
/**
* @param path 请求路径+端口+路由
* @param params 请求参数
* @param resultType 返回接受对象
*/
public static <T> T call(String path, Map<String, Object> params, Type resultType) {
String data = call(path, params);
return JSON.parseObject(data, resultType);
}
public static String call(String path, Map<String, Object> params) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String response = null;
HttpPost httpPostRequest = new HttpPost(path);
CloseableHttpResponse httpResponse = null;
try {
httpPostRequest.setConfig(requestConfig);
httpPostRequest.addHeader("Content-Type", "application/json");
if (params != null) {
StringEntity stringEntity = new StringEntity(JSONObject.toJSONString(params), StandardCharsets.UTF_8);
System.out.println("数据入参格式打印 = " + JSONObject.toJSONString(params));;
stringEntity.setContentEncoding("UTF-8");
httpPostRequest.setEntity(stringEntity);
}
httpResponse = httpClient.execute(httpPostRequest);
// log.info("回参数据打印:{}", ObjectMapper.toJson(httpResponse));
HttpEntity entity = httpResponse.getEntity();
response = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
log.error(e.getMessage(), e);
} finally {
if (httpResponse != null) {
try {
EntityUtils.consume(httpResponse.getEntity());
} catch (IOException e) {
log.error("查看报错信息:{}" + e.getMessage(), e);
}
}
}
log.info("回参数据结束:{}", JSONObject.toJSONString(response));
return response;
}
private static String getCall(String path, Map<String, Object> params) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String response = null;
CloseableHttpResponse httpResponse = null;
try {
URIBuilder uri = new URIBuilder(path);
//get请求带参数
List<NameValuePair> pairList = new ArrayList<>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry
.getValue().toString());
pairList.add(pair);
}
uri.setParameters(pairList);
HttpGet httpGet = new HttpGet(uri.build());
httpGet.setConfig(requestConfig);
httpResponse = httpClient.execute(httpGet);
int statusCode = httpResponse.getStatusLine().getStatusCode();
HttpEntity entity = httpResponse.getEntity();
response = EntityUtils.toString(entity, "UTF-8");
} catch (IOException | URISyntaxException e) {
log.error(e.getMessage(), e);
} finally {
if (httpResponse != null) {
try {
EntityUtils.consume(httpResponse.getEntity());
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return response;
}
public static <T> T callByToken(String path, Map<String, Object> params, String authorization, Type resultType) {
String response = callByToken(path, params, authorization);
return JSONObject.toJSONString(response, resultType);
}
public static String callByToken(String path, Map<String, Object> params, String authorization) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String response = null;
HttpPost httpPostRequest = new HttpPost(path);
CloseableHttpResponse httpResponse = null;
try {
httpPostRequest.setConfig(requestConfig);
httpPostRequest.addHeader("Content-Type", "application/json");
httpPostRequest.addHeader("Authorization", authorization);
if (params != null) {
StringEntity stringEntity = new StringEntity(JSONObject.toJSONString(params), StandardCharsets.UTF_8);
log.info("数据入参格式打印 = " + JSONObject.toJSONString(params));
stringEntity.setContentEncoding("UTF-8");
httpPostRequest.setEntity(stringEntity);
}
httpResponse = httpClient.execute(httpPostRequest);
// log.info("回参数据打印:{}", ObjectMapper.toJson(httpResponse));
HttpEntity entity = httpResponse.getEntity();
response = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
log.error(e.getMessage(), e);
} finally {
if (httpResponse != null) {
try {
EntityUtils.consume(httpResponse.getEntity());
} catch (IOException e) {
log.error("查看报错信息:{}" + e.getMessage(), e);
}
}
}
log.info("回参数据结束:{}", JSONObject.toJSONString(response));
return response;
}
public static String getCall(String token, String path, Map<String, Object> params) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String response = null;
CloseableHttpResponse httpResponse = null;
try {
URIBuilder uri = new URIBuilder(path);
if (!CollectionUtils.isEmpty(params)) {
//get请求带参数
List<NameValuePair> pairList = new ArrayList<>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry
.getValue().toString());
pairList.add(pair);
}
uri.setParameters(pairList);
}
HttpGet httpGet = new HttpGet(uri.build());
httpGet.setConfig(requestConfig);
httpGet.setHeader("Authorization", token);
httpResponse = httpClient.execute(httpGet);
HttpEntity entity = httpResponse.getEntity();
response = EntityUtils.toString(entity, "UTF-8");
} catch (IOException | URISyntaxException e) {
log.error(e.getMessage(), e);
} finally {
if (httpResponse != null) {
try {
EntityUtils.consume(httpResponse.getEntity());
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return response;
}
//获取token
@PostMapping("/index/user/arrears/get")
public Result<HallUserAndAreearsResponse> indexUserAndArrearsGet(long userId, @RequestBody HallBaseRequest request, HttpServletRequest servletRequest) {
String token = servletRequest.getHeader("Authorization");
return hallChargeService.indexUserAndArrearsGet(userId, request, token);
}
//调用接口示例
public void getHttp(String token){
//orderTodoUrl请求地址
Map<String,Object> params =new HashMap<>();
params.put("userCode", userCode);
String call = ApiClient.getCall(token, orderTodoUrl, params);
FlowOrderResponse flowOrderResponse = ObjectMapper.fromJson(call, FlowOrderResponse.class);
}
}
package koi.api.client.helpers;
import koi.api.client.common.Constant;
import koi.api.data.model.resp.LoginResult;
import lombok.extern.slf4j.Slf4j;
import monkey.common.ObjectMapper;
import monkey.common.Result;
import monkey.common.StringHelper;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
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.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.util.CollectionUtils;
import java.io.IOException;
import java.lang.reflect.Type;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
public class KoiApiClient {
private static String API_SERVER = null;
private static String USERNAME = null;
private static String PASSWORD = null;
private static String token = null;
public static void init(String serverPath, String userName, String password) {
API_SERVER = serverPath;
USERNAME = userName;
PASSWORD = password;
token = getToken();
}
public static String getApiServer() {
if (StringHelper.isEmpty(API_SERVER)) {
log.error("请设置服务器地址");
}
return API_SERVER;
}
/**
* 保持心跳,确保token有效
*/
public static void heartbeat() {
Result result = postCall("/api/v1/rabbit/system/member/get/current", new HashMap<>(), Result.class);
if (result == null || !result.isSuccess()) {
log.error("营业系统权限已失效");
token = getToken();
}
}
private static String getToken() {
String path = "/api/v1/rabbit/snt/sso/login";
Map<String, Object> map = new HashMap<>();
map.put("userName", USERNAME);
map.put("password", PASSWORD);
log.info("请求地址:{}",getApiServer());
log.info("用户:{}",USERNAME);
log.info("密码:{}",PASSWORD);
LoginResult loginResult = getCall(path, map, LoginResult.class);
log.info("登录结果:{}",ObjectMapper.toJson(loginResult));
if (loginResult != null && loginResult.getResult() && loginResult.getSuccessed()) {
String message = String.valueOf(loginResult.getMessage());
if (message.startsWith("Bearer ")) {
token = message;
} else {
token = "Bearer " + message;
}
}
return token;
}
public static <T> T getCall(String path, Map<String, Object> params, Type resultType) {
String result = getCall(path, params);
return ObjectMapper.fromJson(result, resultType);
}
public static <T> T postCall(String path, Map<String, Object> params, Type resultType) {
String data = postCall(path, params);
return ObjectMapper.fromJson(data, resultType);
}
public static <T> T postCall(String path, Object jsonObj, Type resultType) {
String data = postCall(path, ObjectMapper.toJson(jsonObj));
return ObjectMapper.fromJson(data, resultType);
}
private static PoolingHttpClientConnectionManager connectionManager;
private static RequestConfig requestConfig;
private static final int MaxConnectTimeout = 2*60000;
static {
// 设置连接池
connectionManager = new PoolingHttpClientConnectionManager();
// 设置连接池大小
connectionManager.setMaxTotal(200);
connectionManager.setDefaultMaxPerRoute(100);
RequestConfig.Builder builder = RequestConfig.custom();
// 设置连接超时
builder.setConnectTimeout(MaxConnectTimeout);
// 设置读取超时
builder.setSocketTimeout(MaxConnectTimeout);
// 设置从连接池获取连接实例的超时
builder.setConnectionRequestTimeout(MaxConnectTimeout);
// 在提交请求之前 测试连接是否可用
requestConfig = builder.build();
}
private static String postCall(String path, String jsonObj) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String response = null;
HttpPost httpPostRequest = null;
try {
httpPostRequest = new HttpPost(getApiServer() + path);
} catch (Exception e) {
e.printStackTrace();
}
CloseableHttpResponse httpResponse = null;
try {
httpPostRequest.setHeader("content-type", "application/json");
httpPostRequest.setConfig(requestConfig);
httpPostRequest.setHeader(Constant.AUTH_KEY, token);
StringEntity stringEntity = new StringEntity(jsonObj, StandardCharsets.UTF_8);
httpPostRequest.setEntity(stringEntity);
httpResponse = httpClient.execute(httpPostRequest);
HttpEntity entity = httpResponse.getEntity();
response = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
System.out.println("请求异常,path:" + path + ",error:" + e.getMessage());
e.printStackTrace();
log.error("请求异常,path:{},error:{}", path, e.getMessage(), e);
} finally {
if (httpResponse != null) {
try {
EntityUtils.consume(httpResponse.getEntity());
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return response;
}
private static String postCall(String path, Map<String, Object> params) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String response = null;
HttpPost httpPostRequest = null;
try {
httpPostRequest = new HttpPost(getApiServer() + path);
} catch (Exception e) {
e.printStackTrace();
}
CloseableHttpResponse httpResponse = null;
try {
httpPostRequest.setHeader("content-type", "application/json");
httpPostRequest.setConfig(requestConfig);
httpPostRequest.setHeader(Constant.AUTH_KEY, token);
StringEntity stringEntity = new StringEntity(ObjectMapper.toJson(params), StandardCharsets.UTF_8);
httpPostRequest.setEntity(stringEntity);
httpResponse = httpClient.execute(httpPostRequest);
HttpEntity entity = httpResponse.getEntity();
response = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
System.out.println("请求异常,path:" + path + ",error:" + e.getMessage());
e.printStackTrace();
log.error("请求异常,path:{},error:{}", path, e.getMessage(), e);
} finally {
if (httpResponse != null) {
try {
EntityUtils.consume(httpResponse.getEntity());
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return response;
}
private static String getCall(String path, Map<String, Object> params) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String response = null;
CloseableHttpResponse httpResponse = null;
try {
URIBuilder uri = new URIBuilder(getApiServer() + path);
if (!CollectionUtils.isEmpty(params)) {
//get请求带参数
List<NameValuePair> pairList = new ArrayList<>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry
.getValue().toString());
pairList.add(pair);
}
uri.setParameters(pairList);
}
HttpGet httpGet = new HttpGet(uri.build());
httpGet.setConfig(requestConfig);
httpResponse = httpClient.execute(httpGet);
HttpEntity entity = httpResponse.getEntity();
response = EntityUtils.toString(entity, "UTF-8");
} catch (IOException | URISyntaxException e) {
log.error(e.getMessage(), e);
} finally {
if (httpResponse != null) {
try {
EntityUtils.consume(httpResponse.getEntity());
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return response;
}
}
调用koiapiclient
public Result<List<UserBatchSaveResponse>> createBatch(long memberId, UserBatchSaveRequest userSaves) {
String apiServer = KoiApiClient.getApiServer();
log.info("接口地址: " + apiServer);
return KoiApiClient.postCall("/api/v1/koi/client/user/create/batch", userSaves, new TypeToken<Result<List<UserBatchSaveResponse>>>() {
}.getType());
}