This commit is contained in:
xiangwb
2017-11-21 13:52:30 +08:00
parent 8bfacd2e22
commit e9e760c1b7
4 changed files with 260 additions and 11 deletions
@@ -1,5 +1,7 @@
package com.xwbing.domain.entity.sys;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.hibernate.validator.constraints.Email;
@@ -20,6 +22,7 @@ import java.util.List;
@EqualsAndHashCode(callSuper = true)
@Data
@Entity(name = "sys_user_info")
@ApiModel
public class SysUser extends BaseEntity {
private static final long serialVersionUID = -2447528751353457021L;
public static String table = "sys_user_info";
@@ -48,22 +51,21 @@ public class SysUser extends BaseEntity {
@NotBlank(message = "性别不能为空")
@Pattern(regexp = "[01]", message = "性别格式为0|1,0代表女,1代表男")
private String sex;
/**
* 盐值
*/
@ApiModelProperty(value = "盐值",hidden = true)
private String salt;
/**
* 密码
*/
@ApiModelProperty(value = "密码",hidden = true)
private String password;
/**
* 是否为管理员
*/
@ApiModelProperty(value = "是否为管理员",hidden = true)
private String admin;
//临时字段
@ApiModelProperty(hidden = true)
private transient String create;
@ApiModelProperty(hidden = true)
private transient String modified;
@ApiModelProperty(hidden = true)
private transient String sexName;
@ApiModelProperty(hidden = true)
private transient List<SysAuthority> menuArray;
@ApiModelProperty(hidden = true)
private transient List<SysAuthority> buttonArray;
}
@@ -0,0 +1,233 @@
package com.xwbing.util;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.*;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.protocol.HttpClientContext;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLException;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.UnsupportedEncodingException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
/**
* 项目名称: boot-module-demo
* 创建时间: 2017/11/21 10:36
* 作者: xiangwb
* 说明: RestClientUtil
*/
public class RestClientUtil {
private static Logger logger = LoggerFactory.getLogger(RestClientUtil.class);
private static PoolingHttpClientConnectionManager poolingHttpClientConnectionManager;
private static final String APPLICATION_JSON = "application/json";
private static final String URL_ERROR = "Request Url can not be empty";
private static final String PARAM_ERROR = "Request Params is null";
/***
* 默认连接配置参数
*/
private static final RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(600000).setConnectTimeout(600000).build();
// Request retry handler
private static HttpRequestRetryHandler retryHandler = (exception, executionCount, context) -> {
logger.info("retryRequest-->");
if (executionCount > 5) {
return false;
}
if (exception instanceof InterruptedIOException) {
// Timeout
return false;
}
if (exception instanceof UnknownHostException) {
// Unknown host
return false;
}
if (exception instanceof SSLException) {
// SSL handshake exception
return false;
}
HttpClientContext clientContext = HttpClientContext.adapt(context);
HttpRequest request = clientContext.getRequest();
return !(request instanceof HttpEntityEnclosingRequest);
};
static {
poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
// 将最大连接数增加到100
poolingHttpClientConnectionManager.setMaxTotal(100);
// 将每个路由基础的连接数增加到20
poolingHttpClientConnectionManager.setDefaultMaxPerRoute(20);
}
private static CloseableHttpClient getHttpClient() {
return HttpClients.custom()
.setConnectionManager(poolingHttpClientConnectionManager)
.setDefaultRequestConfig(defaultRequestConfig)
.setRetryHandler(retryHandler).setConnectionManagerShared(true)
.build();
}
/**
* post请求 json
*
* @param url
* @param param
* @return
*/
public static JSONObject postByJson(String url, JSONObject param) {
if (StringUtils.isEmpty(url)) {
throw new IllegalArgumentException(URL_ERROR);
}
if (param == null) {
throw new IllegalArgumentException(PARAM_ERROR);
}
logger.info("postByJson request URL:{}==================" ,url);
HttpPost post = new HttpPost(url);// 创建HttpPost的实例
post.setEntity(new StringEntity(param.toString(), "UTF-8"));// 设置参数到请求对象中
post.addHeader("Content-Type", APPLICATION_JSON);// 发送json数据需要设置contentType
return getResult(post);
}
/**
* post请求 form
*
* @param url
* @param param
* @return
*/
public static JSONObject postByForm(String url, Map<String, Object> param) {
if (StringUtils.isEmpty(url)) {
throw new IllegalArgumentException(URL_ERROR);
}
if (param == null || param.size() == 0) {
throw new IllegalArgumentException(PARAM_ERROR);
}
logger.info("postByForm request URL:{}================" ,url);
HttpPost post = new HttpPost(url);
// 创建参数队列
List<NameValuePair> params = new ArrayList<>();
for (Map.Entry<String, Object> keys : param.entrySet()) {
params.add(new BasicNameValuePair(keys.getKey(), Objects.toString(keys.getValue())));
}
try {
post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
} catch (UnsupportedEncodingException e) {
logger.error(e.getMessage());
}
return getResult(post);
}
/**
* get请求
*
* @param url
* @return
*/
public static JSONObject get(String url) {
if (StringUtils.isEmpty(url)) {
throw new IllegalArgumentException(URL_ERROR);
}
logger.info("GET request URL:{}======================" ,url);
HttpGet httpGet = new HttpGet(url);
return getResult(httpGet);
}
/**
* put请求
*
* @param url
* @param param
* @return
*/
public static JSONObject put(String url, JSONObject param) {
if (StringUtils.isBlank(url)) {
throw new IllegalArgumentException(URL_ERROR);
}
if (param == null || param.size() == 0) {
throw new IllegalArgumentException(PARAM_ERROR);
}
logger.info("PUT request URL:{}====================",url);
HttpPut put = new HttpPut(url);
put.setEntity(new StringEntity(param.toString(), "UTF-8"));
put.addHeader("Content-type", APPLICATION_JSON);
return getResult(put);
}
/**
* delete请求
*
* @param url
* @return
*/
public static JSONObject delete(String url) {
if (StringUtils.isBlank(url)) {
throw new IllegalArgumentException(URL_ERROR);
}
logger.info("delete request URL:{}=====================" ,url);
HttpDelete delete = new HttpDelete(url);
return getResult(delete);
}
/**
* 获取结果
*
* @param request
* @return
*/
private static JSONObject getResult(HttpRequestBase request) {
JSONObject jsonResult = null;
CloseableHttpClient client = getHttpClient();// 创建HttpClient的实例
try {
long start = System.currentTimeMillis();
CloseableHttpResponse response = client.execute(request);
long end = System.currentTimeMillis();
long ms=end-start;
logger.info("网络接口请求时间为{} ms=======================",ms);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 判断网络连接状态码是否正常(0-200都数正常)
HttpEntity entity = response.getEntity();// 获取结果实体
if (entity != null) {
String result = EntityUtils.toString(entity, "UTF-8");
jsonResult = JSONObject.parseObject(result);
}
}
response.close();
} catch (IOException e) {
// result.setSuccess(false);
// result.setMsg(e.getMessage());
logger.error(e.getMessage());
} finally {
poolingHttpClientConnectionManager.closeExpiredConnections();
poolingHttpClientConnectionManager.closeIdleConnections(120, TimeUnit.MILLISECONDS);
}
return jsonResult;
}
public static void main(String[] args) {
String url = "http://label.drore.com//gis/mapMain/find.json";
JSONObject j = new JSONObject();
JSONObject jr = new JSONObject();
j.put("pageNo", 1);
j.put("pageSize", 10);
jr.put("name", "千岛湖");
j.put("fields", jr);
String ret = postByJson(url, j).toString();
System.out.println(ret);
}
}