Commit 23e98c88 authored by mcb's avatar mcb

no message

parent 7f78a584
...@@ -96,6 +96,13 @@ public class JsonResult<T> implements Serializable { ...@@ -96,6 +96,13 @@ public class JsonResult<T> implements Serializable {
return result; return result;
} }
public static JsonResult<Object> error(String message) {
JsonResult<Object> result = new JsonResult<>();
result.setCode(ResultCode.INTERNAL_SERVER_ERROR);
result.setMessage(message);
return result;
}
public static JsonResult<Object> error(ResultCode code, String message) { public static JsonResult<Object> error(ResultCode code, String message) {
JsonResult<Object> result = new JsonResult<>(); JsonResult<Object> result = new JsonResult<>();
result.setCode(code); result.setCode(code);
......
package com.jz.common.exception; package com.jz.common.exception;
import com.jz.common.constant.ResultCode;
public class ServiceException extends Exception { public class ServiceException extends Exception {
private static final long serialVersionUID = 1859731705152111160L; private static final long serialVersionUID = 1859731705152111160L;
......
package com.jz.common.utils.web; package com.jz.common.utils.web;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair; import org.apache.http.NameValuePair;
...@@ -39,457 +40,442 @@ import java.util.*; ...@@ -39,457 +40,442 @@ import java.util.*;
import java.util.Map.Entry; import java.util.Map.Entry;
/** /**
*
* @author hack2003 * @author hack2003
* @date 2016-10-18
* @version v1.0 * @version v1.0
* * @date 2016-10-18
*/ */
public class HttpClientUtils { public class HttpClientUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientUtils.class); private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientUtils.class);
/** /**
* HttpClient连接SSL * HttpClient连接SSL
*/ */
public void ssl() { public void ssl() {
CloseableHttpClient httpclient = null; CloseableHttpClient httpclient = null;
try { try {
KeyStore trustStore = KeyStore.getInstance(KeyStore KeyStore trustStore = KeyStore.getInstance(KeyStore
.getDefaultType()); .getDefaultType());
FileInputStream instream = new FileInputStream(new File( FileInputStream instream = new FileInputStream(new File(
"d:\\tomcat.keystore")); "d:\\tomcat.keystore"));
try { try {
// 加载keyStore d:\\tomcat.keystore // 加载keyStore d:\\tomcat.keystore
trustStore.load(instream, "123456".toCharArray()); trustStore.load(instream, "123456".toCharArray());
} catch (CertificateException e) { } catch (CertificateException e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
try { try {
instream.close(); instream.close();
} catch (Exception ignore) { } catch (Exception ignore) {
} }
} }
// 相信自己的CA和所有自签名的证书 // 相信自己的CA和所有自签名的证书
SSLContext sslcontext = SSLContexts SSLContext sslcontext = SSLContexts
.custom() .custom()
.loadTrustMaterial(trustStore, .loadTrustMaterial(trustStore,
new TrustSelfSignedStrategy()).build(); new TrustSelfSignedStrategy()).build();
// 只允许使用TLSv1协议 // 只允许使用TLSv1协议
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext, sslcontext,
new String[] { "TLSv1" }, new String[]{"TLSv1"},
null, null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
httpclient = HttpClients.custom().setSSLSocketFactory(sslsf) httpclient = HttpClients.custom().setSSLSocketFactory(sslsf)
.build(); .build();
// 创建http请求(get方式) // 创建http请求(get方式)
HttpGet httpget = new HttpGet( HttpGet httpget = new HttpGet(
"https://localhost:8443/myDemo/Ajax/serivceJ.action"); "https://localhost:8443/myDemo/Ajax/serivceJ.action");
System.out.println("executing request" + httpget.getRequestLine()); System.out.println("executing request" + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget); CloseableHttpResponse response = httpclient.execute(httpget);
try { try {
HttpEntity entity = response.getEntity(); HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
System.out.println(response.getStatusLine()); System.out.println(response.getStatusLine());
if (entity != null) { if (entity != null) {
System.out.println("Response content length: " System.out.println("Response content length: "
+ entity.getContentLength()); + entity.getContentLength());
System.out.println(EntityUtils.toString(entity)); System.out.println(EntityUtils.toString(entity));
EntityUtils.consume(entity); EntityUtils.consume(entity);
} }
} finally { } finally {
response.close(); response.close();
} }
} catch (ParseException e) { } catch (ParseException e) {
e.printStackTrace(); e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} catch (KeyManagementException e) { } catch (KeyManagementException e) {
e.printStackTrace(); e.printStackTrace();
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
e.printStackTrace(); e.printStackTrace();
} catch (KeyStoreException e) { } catch (KeyStoreException e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
if (httpclient != null) { if (httpclient != null) {
try { try {
httpclient.close(); httpclient.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
} }
/** /**
* @discription: * @param url 访问地址
* @param url 访问地址 * @param token 请求头中存放token
* @param token 请求头中存放token * @param json 请求数据体
* @param json 请求数据体 * @return
* @return * @discription:
* @date: 2019年10月25日 * @date: 2019年10月25日
*/ */
public static String postJsonData(String url, String token, String json){ public static String postJsonData(String url, String token, String json) {
LOGGER.info("===================postJsonData start======================="); LOGGER.info("===================postJsonData start=======================");
LOGGER.info("url:"+url); LOGGER.info("url:" + url);
LOGGER.info("token:"+token); LOGGER.info("token:" + token);
LOGGER.info("json:"+json); LOGGER.info("json:" + json);
String charset="UTF-8"; String charset = "UTF-8";
CloseableHttpClient httpClient = null; CloseableHttpClient httpClient = null;
HttpPost httpPost = null; HttpPost httpPost = null;
String result = null; String result = null;
try try {
{
httpClient = HttpClients.createDefault(); httpClient = HttpClients.createDefault();
httpPost = new HttpPost(url); httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(50000).build();//设置请求和传输超时时间 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(50000).build();//设置请求和传输超时时间
httpPost.setConfig(requestConfig); httpPost.setConfig(requestConfig);
httpPost.setHeader("token", token); httpPost.setHeader("token", token);
StringEntity se = new StringEntity(json,"UTF-8"); StringEntity se = new StringEntity(json, "UTF-8");
se.setContentType("application/json"); se.setContentType("application/json");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(se); httpPost.setEntity(se);
LOGGER.info("请求开始时间:"+System.currentTimeMillis()); LOGGER.info("请求开始时间:" + System.currentTimeMillis());
HttpResponse response = httpClient.execute(httpPost); HttpResponse response = httpClient.execute(httpPost);
LOGGER.info("请求结束时间:"+System.currentTimeMillis()); LOGGER.info("请求结束时间:" + System.currentTimeMillis());
if(response != null) if (response != null) {
{ HttpEntity resEntity = response.getEntity();
HttpEntity resEntity = response.getEntity(); if (resEntity != null) {
if(resEntity != null) result = EntityUtils.toString(resEntity, charset);
{ }
result = EntityUtils.toString(resEntity,charset); }
} } catch (Exception ex) {
} LOGGER.info("异常捕捉请求结束时间:" + System.currentTimeMillis());
}catch(Exception ex) ex.printStackTrace();
{
LOGGER.info("异常捕捉请求结束时间:"+System.currentTimeMillis());
ex.printStackTrace();
LOGGER.info(ex.getMessage()); LOGGER.info(ex.getMessage());
} }
LOGGER.info("===================postJsonData end======================="); LOGGER.info("===================postJsonData end=======================");
return result; return result;
}
/**
* post方式提交表单(模拟用户登录请求)
*/
public void postForm() {
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost(
"http://localhost:8080/myDemo/Ajax/serivceJ.action");
// 创建参数队列
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("username", "admin"));
formparams.add(new BasicNameValuePair("password", "123456"));
UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(uefEntity);
System.out.println("executing request " + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity httpEntity = response.getEntity();
if (httpEntity != null) {
System.out
.println("--------------------------------------");
System.out.println("Response content: "
+ EntityUtils.toString(httpEntity, "UTF-8"));
System.out
.println("--------------------------------------");
}
} else {
httppost.abort();
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
if (httpclient != null) {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 发送 get请求
*/
public static void get() {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
// 创建httpget.
HttpGet httpget = new HttpGet("http://www.baidu.com/");
System.out.println("executing request " + httpget.getURI());
// 执行get请求.
CloseableHttpResponse response = httpclient.execute(httpget);
try {
// 获取响应实体
HttpEntity entity = response.getEntity();
System.out.println("--------------------------------------");
// 打印响应状态
System.out.println(response.getStatusLine());
if (entity != null) {
// 打印响应内容长度
System.out.println("Response content length: "
+ entity.getContentLength());
// 打印响应内容
System.out.println("Response content: "
+ EntityUtils.toString(entity));
}
System.out.println("------------------------------------");
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} }
/** /**
* post方式提交表单(模拟用户登录请求) * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
*/ *
public void postForm() { * @return
// 创建默认的httpClient实例. * @throws IOException
CloseableHttpClient httpclient = HttpClients.createDefault(); * @throws ClientProtocolException
// 创建httppost */
HttpPost httppost = new HttpPost( public static String post(String url, String json) {
"http://localhost:8080/myDemo/Ajax/serivceJ.action"); LOGGER.info("===================POST request start=======================");
// 创建参数队列 LOGGER.info("url:" + url);
List<NameValuePair> formparams = new ArrayList<NameValuePair>(); LOGGER.info("json:" + json);
formparams.add(new BasicNameValuePair("username", "admin")); String charset = "UTF-8";
formparams.add(new BasicNameValuePair("password", "123456")); CloseableHttpClient httpClient = null;
UrlEncodedFormEntity uefEntity; HttpPost httpPost = null;
try { String result = null;
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8"); try {
httppost.setEntity(uefEntity);
System.out.println("executing request " + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity httpEntity = response.getEntity();
if (httpEntity != null) {
System.out
.println("--------------------------------------");
System.out.println("Response content: "
+ EntityUtils.toString(httpEntity, "UTF-8"));
System.out
.println("--------------------------------------");
}
} else {
httppost.abort();
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
if (httpclient != null) {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 发送 get请求
*/
public static void get() {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
// 创建httpget.
HttpGet httpget = new HttpGet("http://www.baidu.com/");
System.out.println("executing request " + httpget.getURI());
// 执行get请求.
CloseableHttpResponse response = httpclient.execute(httpget);
try {
// 获取响应实体
HttpEntity entity = response.getEntity();
System.out.println("--------------------------------------");
// 打印响应状态
System.out.println(response.getStatusLine());
if (entity != null) {
// 打印响应内容长度
System.out.println("Response content length: "
+ entity.getContentLength());
// 打印响应内容
System.out.println("Response content: "
+ EntityUtils.toString(entity));
}
System.out.println("------------------------------------");
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 发送 post请求访问本地应用并根据传递参数不同返回不同结果
* @return
*
* @throws IOException
* @throws ClientProtocolException
*/
public static String post(String url,String json)
{
String charset="UTF-8";
CloseableHttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try
{
httpClient = HttpClients.createDefault(); httpClient = HttpClients.createDefault();
httpPost = new HttpPost(url); httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(50000).build();//设置请求和传输超时时间 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(50000).build();//设置请求和传输超时时间
httpPost.setConfig(requestConfig); httpPost.setConfig(requestConfig);
StringEntity se = new StringEntity(json,"UTF-8"); StringEntity se = new StringEntity(json, "UTF-8");
se.setContentType("application/json"); se.setContentType("application/json");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
System.out.println("-------------"+ JSONObject.toJSONString(se)); System.out.println("-------------" + JSONObject.toJSONString(se));
httpPost.setEntity(se); httpPost.setEntity(se);
HttpResponse response = httpClient.execute(httpPost); HttpResponse response = httpClient.execute(httpPost);
if(response != null) if (response != null) {
{ HttpEntity resEntity = response.getEntity();
HttpEntity resEntity = response.getEntity(); if (resEntity != null) {
if(resEntity != null) result = EntityUtils.toString(resEntity, charset);
{ }
result = EntityUtils.toString(resEntity,charset); }
} } catch (Exception ex) {
} ex.printStackTrace();
}catch(Exception ex) }
{ LOGGER.info("===================POST request end=======================");
ex.printStackTrace(); return result;
}
return result;
} }
/** /**
* 带参 * 带参
* @param url *
* @param paramName * @param url
* @param json * @param paramName
* @return * @param json
*/ * @return
public static String post(String url,String paramName,String json) */
{ public static String post(String url, String paramName, String json) {
String charset="UTF-8"; String charset = "UTF-8";
CloseableHttpClient httpClient = null; CloseableHttpClient httpClient = null;
HttpPost httpPost = null; HttpPost httpPost = null;
String result = null; String result = null;
try try {
{ httpClient = HttpClients.createDefault();
httpClient = HttpClients.createDefault(); httpPost = new HttpPost(url);
httpPost = new HttpPost(url); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();//设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();//设置请求和传输超时时间 httpPost.setConfig(requestConfig);
httpPost.setConfig(requestConfig); List<NameValuePair> list = new LinkedList<>();
List<NameValuePair> list = new LinkedList<>(); BasicNameValuePair param1 = new BasicNameValuePair(paramName, json);
BasicNameValuePair param1 = new BasicNameValuePair(paramName, json); list.add(param1);
list.add(param1);
// StringEntity se = new StringEntity(json,"UTF-8"); // StringEntity se = new StringEntity(json,"UTF-8");
// se.setContentType("application/json"); // se.setContentType("application/json");
// se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); // se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, "UTF-8"); UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, "UTF-8");
// entityParam.setContentType("application/json"); // entityParam.setContentType("application/json");
// entityParam.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); // entityParam.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(entityParam); httpPost.setEntity(entityParam);
HttpResponse response = httpClient.execute(httpPost); HttpResponse response = httpClient.execute(httpPost);
if(response != null) if (response != null) {
{ HttpEntity resEntity = response.getEntity();
HttpEntity resEntity = response.getEntity(); if (resEntity != null) {
if(resEntity != null) result = EntityUtils.toString(resEntity, charset);
{ }
result = EntityUtils.toString(resEntity,charset); }
} } catch (Exception ex) {
} ex.printStackTrace();
}catch(Exception ex) }
{ return result;
ex.printStackTrace(); }
}
return result;
} /**
* 提交JSON参数
*
/** * @param url
* 提交JSON参数 * @param paramName
* @param url * @param json
* @param paramName * @return
* @param json */
* @return public static String postJson(String url, String paramName, String json) {
*/ String charset = "UTF-8";
public static String postJson(String url,String paramName,String json) CloseableHttpClient httpClient = null;
{ HttpPost httpPost = null;
String charset="UTF-8"; String result = null;
CloseableHttpClient httpClient = null; try {
HttpPost httpPost = null; httpClient = HttpClients.createDefault();
String result = null; httpPost = new HttpPost(url);
try RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();//设置请求和传输超时时间
{ httpPost.setConfig(requestConfig);
httpClient = HttpClients.createDefault();
httpPost = new HttpPost(url); StringEntity se = new StringEntity(json, "UTF-8");
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();//设置请求和传输超时时间 se.setContentType("application/json");
httpPost.setConfig(requestConfig); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(se);
StringEntity se = new StringEntity(json,"UTF-8"); HttpResponse response = httpClient.execute(httpPost);
se.setContentType("application/json"); if (response != null) {
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); HttpEntity resEntity = response.getEntity();
httpPost.setEntity(se); if (resEntity != null) {
HttpResponse response = httpClient.execute(httpPost); result = EntityUtils.toString(resEntity, charset);
if(response != null) }
{ }
HttpEntity resEntity = response.getEntity(); } catch (Exception ex) {
if(resEntity != null) ex.printStackTrace();
{ }
result = EntityUtils.toString(resEntity,charset); return result;
} }
}
}catch(Exception ex) public static String dopost(String url, String json) throws ClientProtocolException, IOException {
{ String result = null;
ex.printStackTrace(); String APPLICATION_JSON = "application/json";
} String charset = "UTF-8";
return result; // 将JSON进行UTF-8编码,以便传输中文
} String encoderJson = URLEncoder.encode(json, charset);
CloseableHttpClient httpclient = HttpClients.createDefault();
public static String dopost(String url, String json) throws ClientProtocolException,IOException { HttpPost httppost = new HttpPost(url);
String result=null; httppost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
String APPLICATION_JSON = "application/json"; StringEntity stringEntity = new StringEntity(encoderJson);
String charset="UTF-8"; stringEntity.setContentType("text/json");
// 将JSON进行UTF-8编码,以便传输中文 stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
String encoderJson = URLEncoder.encode(json, charset); httppost.setEntity(stringEntity);
CloseableHttpClient httpclient = HttpClients.createDefault(); //System.out.println("executing request " + httppost.getURI());
HttpPost httppost = new HttpPost(url); CloseableHttpResponse response = httpclient.execute(httppost);
httppost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON); if (response.getStatusLine().getStatusCode() == 200) {
StringEntity stringEntity = new StringEntity(encoderJson); HttpEntity httpEntity = response.getEntity();
stringEntity.setContentType("text/json"); if (httpEntity != null) {
stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,APPLICATION_JSON)); System.out.println("Response content: " + EntityUtils.toString(httpEntity, charset));
httppost.setEntity(stringEntity); result = EntityUtils.toString(httpEntity, charset);
//System.out.println("executing request " + httppost.getURI()); }
CloseableHttpResponse response = httpclient.execute(httppost); } else {
if (response.getStatusLine().getStatusCode() == 200) { httppost.abort();
HttpEntity httpEntity = response.getEntity(); }
if (httpEntity != null) { response.close();
System.out.println("Response content: "+ EntityUtils.toString(httpEntity, charset)); if (httpclient != null) {
result = EntityUtils.toString(httpEntity,charset); try {
} httpclient.close();
} else { } catch (IOException e) {
httppost.abort(); e.printStackTrace();
} }
response.close(); }
if (httpclient != null) { return result;
try { }
httpclient.close();
} catch (IOException e) { /**
e.printStackTrace(); * http请求资源,json不编码
} *
} * @param url
return result; * @param json
} * @return
* @throws ClientProtocolException
/**http请求资源,json不编码 * @throws IOException
* @param url */
* @param json public static String dopostNoEncode(String url, String json) throws ClientProtocolException, IOException {
* @return String result = null;
* @throws ClientProtocolException String APPLICATION_JSON = "application/json";
* @throws IOException String charset = "UTF-8";
*/ // 将JSON进行UTF-8编码,以便传输中文
public static String dopostNoEncode(String url, String json) throws ClientProtocolException,IOException { CloseableHttpClient httpclient = HttpClients.createDefault();
String result=null; HttpPost httppost = new HttpPost(url);
String APPLICATION_JSON = "application/json"; httppost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
String charset="UTF-8"; StringEntity stringEntity = new StringEntity(json, charset);
// 将JSON进行UTF-8编码,以便传输中文 stringEntity.setContentType("text/json");
CloseableHttpClient httpclient = HttpClients.createDefault(); stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
HttpPost httppost = new HttpPost(url); httppost.setEntity(stringEntity);
httppost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON); //System.out.println("executing request " + httppost.getURI());
StringEntity stringEntity = new StringEntity(json, charset); CloseableHttpResponse response = httpclient.execute(httppost);
stringEntity.setContentType("text/json"); if (response.getStatusLine().getStatusCode() == 200) {
stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,APPLICATION_JSON)); HttpEntity httpEntity = response.getEntity();
httppost.setEntity(stringEntity); if (httpEntity != null) {
//System.out.println("executing request " + httppost.getURI()); //System.out.println("Response content: "+ EntityUtils.toString(httpEntity, charset));
CloseableHttpResponse response = httpclient.execute(httppost); result = EntityUtils.toString(httpEntity, charset);
if (response.getStatusLine().getStatusCode() == 200) { }
HttpEntity httpEntity = response.getEntity(); } else {
if (httpEntity != null) { httppost.abort();
//System.out.println("Response content: "+ EntityUtils.toString(httpEntity, charset)); }
result = EntityUtils.toString(httpEntity,charset); response.close();
} if (httpclient != null) {
} else { try {
httppost.abort(); httpclient.close();
} } catch (IOException e) {
response.close(); e.printStackTrace();
if (httpclient != null) { }
try { }
httpclient.close(); return result;
} catch (IOException e) { }
e.printStackTrace();
}
} /**
return result; * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
} *
* @return
* @throws IOException
/** * @throws ClientProtocolException
* 发送 post请求访问本地应用并根据传递参数不同返回不同结果 */
* @return public static String postJson(String url, com.alibaba.fastjson.JSONObject json) {
* String charset = "UTF-8";
* @throws IOException CloseableHttpClient httpClient = null;
* @throws ClientProtocolException HttpPost httpPost = null;
*/ String result = null;
public static String postJson(String url, com.alibaba.fastjson.JSONObject json) try {
{
String charset="UTF-8";
CloseableHttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try
{
httpClient = HttpClients.createDefault(); httpClient = HttpClients.createDefault();
httpPost = new HttpPost(url); httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();//设置请求和传输超时时间 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();//设置请求和传输超时时间
...@@ -498,196 +484,200 @@ public class HttpClientUtils { ...@@ -498,196 +484,200 @@ public class HttpClientUtils {
se.setContentType("application/json"); se.setContentType("application/json");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(se); httpPost.setEntity(se);
HttpResponse response = httpClient.execute(httpPost); HttpResponse response = httpClient.execute(httpPost);
if(response != null) if (response != null) {
{ HttpEntity resEntity = response.getEntity();
HttpEntity resEntity = response.getEntity(); if (resEntity != null) {
if(resEntity != null) result = EntityUtils.toString(resEntity, charset);
{ }
result = EntityUtils.toString(resEntity,charset); }
} } catch (Exception ex) {
} ex.printStackTrace();
}catch(Exception ex) }
{ return result;
ex.printStackTrace();
}
return result;
} }
/**
/** * get请求,返回字节数组
* get请求,返回字节数组 *
* * @param url
* @param url * @param params
* @param params * @param headers
* @param headers * @return
* @return * @throws IOException
* @throws IOException * @throws ClientProtocolException
* @throws ClientProtocolException */
*/ public static byte[] doGetByByte(String url, Map<String, String> params, Map<String, String> headers) throws IOException {
public static byte[] doGetByByte(String url, Map<String, String> params, Map<String, String> headers) throws IOException { LOGGER.info("===================doGetByByte start =======================");
LOGGER.info("===================doGetByByte start ======================="); // 参数
// 参数 StringBuilder paramsBuilder = new StringBuilder(url);
StringBuilder paramsBuilder = new StringBuilder(url); byte[] responseContent = null;
byte[] responseContent = null; if (params != null && !params.keySet().isEmpty()) {
if (params != null && !params.keySet().isEmpty()) { if (url.indexOf("?") == -1) {
if (url.indexOf("?") == -1) { paramsBuilder.append("?");
paramsBuilder.append("?"); }
} List<NameValuePair> list = new ArrayList<>();
List<NameValuePair> list = new ArrayList<>();
Set<String> keySet = params.keySet();
Set<String> keySet = params.keySet(); Iterator<String> iterator = keySet.iterator();
Iterator<String> iterator = keySet.iterator(); while (iterator.hasNext()) {
while (iterator.hasNext()) { String key = iterator.next();
String key = iterator.next(); String value = params.get(key);
String value = params.get(key); list.add(new BasicNameValuePair(key, value));
list.add(new BasicNameValuePair(key, value)); }
} String paramsStr = EntityUtils.toString(new UrlEncodedFormEntity(list));
String paramsStr = EntityUtils.toString(new UrlEncodedFormEntity(list)); paramsBuilder.append(paramsStr);
paramsBuilder.append(paramsStr); }
} HttpGet httpGet = new HttpGet(paramsBuilder.toString());
HttpGet httpGet = new HttpGet(paramsBuilder.toString()); // 头
// 头 if (headers != null && !headers.keySet().isEmpty()) {
if (headers != null && !headers.keySet().isEmpty()) { Set<String> keySet = headers.keySet();
Set<String> keySet = headers.keySet(); Iterator<String> iterator = keySet.iterator();
Iterator<String> iterator = keySet.iterator(); while (iterator.hasNext()) {
while (iterator.hasNext()) { String key = iterator.next();
String key = iterator.next(); String value = headers.get(key);
String value = headers.get(key); httpGet.addHeader(key, value);
httpGet.addHeader(key, value); }
} }
} try {
try { CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(httpGet);
CloseableHttpResponse response = httpClient.execute(httpGet); HttpEntity resEntity = null;
HttpEntity resEntity=null; if (response.getStatusLine().getStatusCode() == 200) { // 请求成功状态
if (response.getStatusLine().getStatusCode() == 200) { // 请求成功状态 resEntity = response.getEntity();
resEntity = response.getEntity(); }
} if (resEntity != null) {
if(resEntity != null){ responseContent = EntityUtils.toByteArray(resEntity);
responseContent = EntityUtils.toByteArray(resEntity);
// result = EntityUtils.toString(resEntity,charset); // result = EntityUtils.toString(resEntity,charset);
} }
} catch (Exception e) { } catch (Exception e) {
LOGGER.info("异常捕捉请求结束时间:"+System.currentTimeMillis()); LOGGER.info("异常捕捉请求结束时间:" + System.currentTimeMillis());
e.printStackTrace(); e.printStackTrace();
LOGGER.info(e.getMessage()); LOGGER.info(e.getMessage());
} }
LOGGER.info("===================doGetByByte end======================="); LOGGER.info("===================doGetByByte end=======================");
return responseContent; return responseContent;
} }
/** /**
* @discription: * @param url 访问地址
* @param url 访问地址 * @param token 请求头中存放token
* @param token 请求头中存放token * @param json 请求数据体
* @param json 请求数据体 * @return
* @return * @discription:
* @date: 2019年10月25日 * @date: 2019年10月25日
*/ */
public static byte[] postJsonDataByByte(String url, String token, String json){ public static byte[] postJsonDataByByte(String url, String token, String json) {
LOGGER.info("===================postJsonDataByByte start======================="); LOGGER.info("===================postJsonDataByByte start=======================");
LOGGER.info("url:"+url); LOGGER.info("url:" + url);
LOGGER.info("token:"+token); LOGGER.info("token:" + token);
LOGGER.info("json:"+json); LOGGER.info("json:" + json);
String charset="UTF-8"; String charset = "UTF-8";
CloseableHttpClient httpClient = null; CloseableHttpClient httpClient = null;
HttpPost httpPost = null; HttpPost httpPost = null;
String result = null; String result = null;
byte[] responseContent = null; byte[] responseContent = null;
try try {
{
httpClient = HttpClients.createDefault(); httpClient = HttpClients.createDefault();
httpPost = new HttpPost(url); httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(50000).build();//设置请求和传输超时时间 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(50000).build();//设置请求和传输超时时间
httpPost.setConfig(requestConfig); httpPost.setConfig(requestConfig);
httpPost.setHeader("token", token); httpPost.setHeader("token", token);
StringEntity se = new StringEntity(json,"UTF-8"); StringEntity se = new StringEntity(json, "UTF-8");
se.setContentType("application/json"); se.setContentType("application/json");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(se); httpPost.setEntity(se);
LOGGER.info("请求开始时间:"+System.currentTimeMillis()); LOGGER.info("请求开始时间:" + System.currentTimeMillis());
HttpResponse response = httpClient.execute(httpPost); HttpResponse response = httpClient.execute(httpPost);
LOGGER.info("请求结束时间:"+System.currentTimeMillis()); LOGGER.info("请求结束时间:" + System.currentTimeMillis());
if(response != null){ if (response != null) {
HttpEntity resEntity = response.getEntity(); HttpEntity resEntity = response.getEntity();
if(response.getStatusLine().getStatusCode() == 200) { if (response.getStatusLine().getStatusCode() == 200) {
if(resEntity != null){ if (resEntity != null) {
responseContent = EntityUtils.toByteArray(resEntity); responseContent = EntityUtils.toByteArray(resEntity);
} }
}else { } else {
LOGGER.info("请求失败:"+EntityUtils.toString(resEntity,charset)); LOGGER.info("请求失败:" + EntityUtils.toString(resEntity, charset));
return responseContent; return responseContent;
} }
} }
}catch(Exception ex){ } catch (Exception ex) {
LOGGER.info("异常捕捉请求结束时间:"+System.currentTimeMillis()); LOGGER.info("异常捕捉请求结束时间:" + System.currentTimeMillis());
ex.printStackTrace(); ex.printStackTrace();
LOGGER.info(ex.getMessage()); LOGGER.info(ex.getMessage());
} }
LOGGER.info("===================postJsonDataByByte end======================="); LOGGER.info("===================postJsonDataByByte end=======================");
return responseContent; return responseContent;
} }
/** /**
* 发送 getJsonForParam请求 * 发送 getJsonForParam请求
*/ * @author Bellamy
public static String getJsonForParam(String url, Map<String, Object> paramMap) { */
LOGGER.info("===================getJsonForParam start======================="); public static String getJsonForParam(String url, Map<String, Object> paramMap) {
LOGGER.info("url:" + url); LOGGER.info("===================Get request getJsonForParam start=======================");
LOGGER.info("json:" + paramMap); LOGGER.info("url:" + url);
LOGGER.info("json:" + paramMap);
String result = null; String result = null;
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (Entry<String, Object> entry : paramMap.entrySet()) { String fh = "";
sb.append("&"); if (paramMap != null) {
sb.append(entry.getKey()); if (url.indexOf("?") == -1) {
sb.append("="); fh = "?";
sb.append(entry.getValue()); }
} for (Entry<String, Object> entry : paramMap.entrySet()) {
sb.append("&");
String requestUrl = url+sb.toString(); sb.append(entry.getKey());
sb.append("=");
CloseableHttpClient httpclient = HttpClients.createDefault(); sb.append(entry.getValue());
try { }
// 创建httpget. }
HttpGet httpget = new HttpGet(requestUrl); if (StringUtils.isNotEmpty(sb)) {
System.out.println("executing request " + httpget.getURI()); fh += sb.toString().substring(1);
// 执行get请求. }
CloseableHttpResponse response = httpclient.execute(httpget);
// 获取响应实体 String requestUrl = url + fh;
HttpEntity entity = response.getEntity();
System.out.println("--------------------------------------"); CloseableHttpClient httpclient = HttpClients.createDefault();
// 打印响应状态 try {
System.out.println(response.getStatusLine()); // 创建httpget.
if (entity != null) { HttpGet httpget = new HttpGet(requestUrl);
result = EntityUtils.toString(entity); System.out.println("get executing request " + httpget.getURI());
LOGGER.info(result); // 执行get请求.
} CloseableHttpResponse response = httpclient.execute(httpget);
// 获取响应实体
} catch (ClientProtocolException e) { HttpEntity entity = response.getEntity();
e.printStackTrace(); System.out.println("--------------------------------------");
} catch (ParseException e) { // 打印响应状态
e.printStackTrace(); System.out.println(response.getStatusLine());
} catch (IOException e) { if (entity != null) {
e.printStackTrace(); result = EntityUtils.toString(entity);
} LOGGER.info(result);
}
LOGGER.info("===================getJsonForParam end=======================");
return result; } catch (ClientProtocolException e) {
e.printStackTrace();
} } catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
public static void main(String[] args) throws Exception { }
// 私钥
LOGGER.info("===================getJsonForParam end=======================");
return result;
}
public static void main(String[] args) throws Exception {
// 私钥
/*String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJzAfk55exxmvy3+pXsJINZEtmwUp6eBfDSl2YnT5bdJL3nzPnSjmaWsf8x9hR4QyGnvlV/Vo0sk36X7ATcqxfIn0+6W5f8IR4XtVDhxZsD/cK8nVThqFGQagmyNAwxP/wBnAXOy+fpwZrMOgqfosYmVsmImFWbHA87C4mx0bwoJAgMBAAECgYB4tlBOVIT3ITTW0cRT1HrCJxYoc1uMxk2FKbc1ycWceTKjgiu1nQtEp2ufaYYq2hfMZOEudRIUWygT5RFRj5HxLfL6Me3y6dtgyHvOVeMDNGAG+tsn8ObQCQjZ/hVKzFFgHlrHv5i4zX44im2IdvLqnV6cEUneduJfZAQT/XTGUQJBANAZbuTqlDRj/9ObGZEvaPe95FGAPNFEiNmRvLsCsRmruJA5h2ogwx8O4Yll5LylKV6C33Vws4pgAPBHvOzGTx0CQQDA1VYU4ihNyvMknFIAmMT2ojQmQ8ASX64hVFWY9ehf5JaJ+ZD1c1BvbrmubpIo7pPci50BmXnjq6EcxVML/VbdAkAwEH/FjczXYPV4yY0ZNIsZFZoDnQvvBdZZ8khWJWQEWt5RKYh2YcTPip9bHda8H6Wzd6TnOjWt00jENr2TLqadAkEAq0TQD/xOj8mR6xJsQtttFSE78EB8d9VDc5bT7+d5XLJKgoGGnnqtFkvh32uVpYVBDsFx0dneyLfHgSZBfISmgQJADZ71qrfCDvuoYNS4aOW52OL6LMC84Qi2EnZzl5OHkUuOv5jwBoOCRLEn0N999EMP6DBg8P5kg1llTq7bMG11ug=="; /*String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJzAfk55exxmvy3+pXsJINZEtmwUp6eBfDSl2YnT5bdJL3nzPnSjmaWsf8x9hR4QyGnvlV/Vo0sk36X7ATcqxfIn0+6W5f8IR4XtVDhxZsD/cK8nVThqFGQagmyNAwxP/wBnAXOy+fpwZrMOgqfosYmVsmImFWbHA87C4mx0bwoJAgMBAAECgYB4tlBOVIT3ITTW0cRT1HrCJxYoc1uMxk2FKbc1ycWceTKjgiu1nQtEp2ufaYYq2hfMZOEudRIUWygT5RFRj5HxLfL6Me3y6dtgyHvOVeMDNGAG+tsn8ObQCQjZ/hVKzFFgHlrHv5i4zX44im2IdvLqnV6cEUneduJfZAQT/XTGUQJBANAZbuTqlDRj/9ObGZEvaPe95FGAPNFEiNmRvLsCsRmruJA5h2ogwx8O4Yll5LylKV6C33Vws4pgAPBHvOzGTx0CQQDA1VYU4ihNyvMknFIAmMT2ojQmQ8ASX64hVFWY9ehf5JaJ+ZD1c1BvbrmubpIo7pPci50BmXnjq6EcxVML/VbdAkAwEH/FjczXYPV4yY0ZNIsZFZoDnQvvBdZZ8khWJWQEWt5RKYh2YcTPip9bHda8H6Wzd6TnOjWt00jENr2TLqadAkEAq0TQD/xOj8mR6xJsQtttFSE78EB8d9VDc5bT7+d5XLJKgoGGnnqtFkvh32uVpYVBDsFx0dneyLfHgSZBfISmgQJADZ71qrfCDvuoYNS4aOW52OL6LMC84Qi2EnZzl5OHkUuOv5jwBoOCRLEn0N999EMP6DBg8P5kg1llTq7bMG11ug==";
RequestCSVFileParamBean bean = new RequestCSVFileParamBean(); RequestCSVFileParamBean bean = new RequestCSVFileParamBean();
bean.setGetFile("1.csv"); bean.setGetFile("1.csv");
...@@ -697,7 +687,7 @@ public class HttpClientUtils { ...@@ -697,7 +687,7 @@ public class HttpClientUtils {
HttpClientUtils http = new HttpClientUtils(); HttpClientUtils http = new HttpClientUtils();
String url = "http://127.0.0.1:8080/mysales_interface/getExtCsvFile"; String url = "http://127.0.0.1:8080/mysales_interface/getExtCsvFile";
http.post(url,JSON.toJSONString(bean));*/ http.post(url,JSON.toJSONString(bean));*/
} }
} }
package com.jz.dmp.modules.controller.dataService; package com.jz.dmp.modules.controller.dataService;
import com.jz.common.constant.JsonResult;
import com.jz.common.constant.ResultCode;
import com.jz.dmp.modules.controller.dataOperation.bean.DataDevTaskListDto;
import com.jz.dmp.modules.controller.dataService.bean.OrganizationManageAddReq;
import com.jz.dmp.modules.controller.dataService.bean.OrganizationManageListQueryReq;
import com.jz.dmp.modules.controller.dataService.bean.OrganizationManageUpdateReq;
import com.jz.dmp.modules.service.DmpOrgMangeService; import com.jz.dmp.modules.service.DmpOrgMangeService;
import com.jz.dmp.modules.service.DvRuleTService;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
/** /**
* 数据服务组织管理 * 数据服务组织管理--调用gateway 接口
* *
* @author Bellamy * @author Bellamy
* @since 2020-12-24 10:56:18 * @since 2020-12-24 10:56:18
...@@ -17,11 +29,102 @@ import org.springframework.web.bind.annotation.RestController; ...@@ -17,11 +29,102 @@ import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/orgMange") @RequestMapping("/orgMange")
@Api(tags = "数据服务-组织管理") @Api(tags = "数据服务-组织管理")
public class DmpOrgMangeController { public class DmpOrgMangeController {
private static Logger logger = LoggerFactory.getLogger(DmpOrgMangeController.class);
/** /**
* 服务对象 * 服务对象
*/ */
@Autowired @Autowired
private DmpOrgMangeService dmpOrgMangeService; private DmpOrgMangeService dmpOrgMangeService;
/**
* 列表分页查询
*
* @return
* @author Bellamy
* @since 2021-01-16
*/
@ApiOperation(value = "列表分页查询", notes = "列表分页查询")
@PostMapping(value = "/listPage")
public JsonResult getOrgListPage(@RequestBody @Validated OrganizationManageListQueryReq req, HttpServletRequest httpRequest) {
JsonResult jsonResult = new JsonResult();
try {
jsonResult = dmpOrgMangeService.queryOrgListPage(req);
} catch (Exception e) {
jsonResult.setMessage(e.getMessage());
jsonResult.setCode(ResultCode.INTERNAL_SERVER_ERROR);
e.printStackTrace();
}
return jsonResult;
}
/**
* 删除组织
*
* @return
* @author Bellamy
* @since 2021-01-16
*/
@ApiOperation(value = "删除组织", notes = "删除组织")
@GetMapping(value = "/delOrg")
@ApiImplicitParam(name = "id",value = "组织id",required = true)
public JsonResult delOrgById(@RequestParam long id, HttpServletRequest httpRequest) {
JsonResult jsonResult = new JsonResult();
try {
jsonResult = dmpOrgMangeService.delOrgById(id);
} catch (Exception e) {
jsonResult.setMessage(e.getMessage());
jsonResult.setCode(ResultCode.INTERNAL_SERVER_ERROR);
e.printStackTrace();
}
return jsonResult;
}
/**
* 新增组织
*
* @return
* @author Bellamy
* @since 2021-01-16
*/
@ApiOperation(value = "新增组织", notes = "新增组织")
@PostMapping(value = "/addOrg")
public JsonResult addOrg(@RequestBody @Validated OrganizationManageAddReq req, HttpServletRequest httpRequest) {
if (StringUtils.isEmpty(req.getOrgName())) {
return JsonResult.error(ResultCode.PARAMS_ERROR,"组织名称不能为空!");
}
if (StringUtils.isEmpty(req.getOrgType())) {
return JsonResult.error(ResultCode.PARAMS_ERROR,"组织类型不能为空!");
}
JsonResult jsonResult = new JsonResult();
try {
jsonResult = dmpOrgMangeService.addOrg(req);
} catch (Exception e) {
jsonResult.setMessage(e.getMessage());
jsonResult.setCode(ResultCode.INTERNAL_SERVER_ERROR);
e.printStackTrace();
}
return jsonResult;
}
/**
* 编辑组织
*
* @return
* @author Bellamy
* @since 2021-01-16
*/
@ApiOperation(value = "编辑组织", notes = "编辑组织")
@PostMapping(value = "/updateOrg")
public JsonResult updateOrg(@RequestBody @Validated OrganizationManageUpdateReq req, HttpServletRequest httpRequest) {
JsonResult jsonResult = new JsonResult();
try {
jsonResult = dmpOrgMangeService.updateOrg(req);
} catch (Exception e) {
jsonResult.setMessage(e.getMessage());
jsonResult.setCode(ResultCode.INTERNAL_SERVER_ERROR);
e.printStackTrace();
}
return jsonResult;
}
} }
\ No newline at end of file
package com.jz.dmp.modules.controller.dataService.bean;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
/**
* @ClassName: OrganizationManageAddReq
* @Description: 新增组织管理请求体
* @Author: Bellamy
* @Date 2021/1/16
* @Version 1.0
*/
@Data
@ApiModel("新增组织管理详情请求体")
public class OrganizationManageAddReq implements Serializable {
private static final long serialVersionUID = 3131683881168540907L;
@ApiModelProperty(value = "组织类型:INT 内部组织 OUT 外部组织", required = true)
@NotNull(message = "组织类型不能为空!")
@NotEmpty(message = "组织类型不能为空!")
private String orgType;
@ApiModelProperty(value = "组织名称", required = true)
@NotNull(message = "组织名称不能为空")
@NotEmpty(message = "组织名称不能为空!")
private String orgName;
@ApiModelProperty(value = "组织描述", required = false)
private String orgDesc;
@ApiModelProperty(value = "组织英文名称", required = false)
private String orgCnName;
@ApiModelProperty(value = "组织邮箱", required = false)
private String orgMail;
@ApiModelProperty(value = "联系方式", required = true)
@NotEmpty(message = "联系方式不能为空!")
private String orgPhone;
@ApiModelProperty(value = "状态(NORMAL-正常 FREEZE-冻结 CANCEL-注销)", required = true)
private String status;
@ApiModelProperty(value = "联系人", required = true)
private String createUser;
}
package com.jz.dmp.modules.controller.dataService.bean;
import com.jz.common.bean.BasePageBean;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* @ClassName: DmpOrgMangeService
* @Description: 组织管理列表查询请求体
* @Author: Bellamy
* @Date 2021/1/16
* @Version 1.0
*/
@Data
@ApiModel("组织管理列表查询请求体")
public class OrganizationManageListQueryReq extends BasePageBean implements Serializable {
@ApiModelProperty(value = "组织名称")
private String orgName;
@ApiModelProperty(value = "组织编码(组织唯一标识)")
private String orgCode;
}
package com.jz.dmp.modules.controller.dataService.bean;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
/**
* @ClassName: OrganizationManageUpdateReq
* @Description: 更新组织管理请求体
* @Author: Bellamy
* @Date 2021/1/16
* @Version 1.0
*/
@Data
@ApiModel("更新组织管理请求体")
public class OrganizationManageUpdateReq implements Serializable {
@ApiModelProperty(value = "组织id",required = true)
@NotNull(message = "组织id不能为空")
private Long id;
/* @ApiModelProperty(value = "组织名称",required = true)
@NotNull(message = "组织名称不能为空")
private String orgName;*/
@ApiModelProperty(value = "组织描述",required = false)
private String orgDesc;
@ApiModelProperty(value = "状态(NORMAL-正常 FREEZE-冻结 CANCEL-注销)",required = false)
private String status;
@ApiModelProperty(value = "组织英文名称",required = false)
private String orgCnName;
@ApiModelProperty(value = "组织邮箱",required = false)
private String orgMail;
@ApiModelProperty(value = "组织电话",required = false)
private String orgPhone;
@ApiModelProperty(value = "备注",required = false)
private String remark;
@ApiModelProperty(value = "创建用户",required = false)
private String updateUser;
}
package com.jz.dmp.modules.service; package com.jz.dmp.modules.service;
import com.jz.common.constant.JsonResult;
import com.jz.dmp.modules.controller.dataService.bean.OrganizationManageAddReq;
import com.jz.dmp.modules.controller.dataService.bean.OrganizationManageListQueryReq;
import com.jz.dmp.modules.controller.dataService.bean.OrganizationManageUpdateReq;
/** /**
* @ClassName: DmpOrgMangeService * @ClassName: DmpOrgMangeService
* @Description: 数据服务组织管理 * @Description: 数据服务组织管理
...@@ -8,4 +13,40 @@ package com.jz.dmp.modules.service; ...@@ -8,4 +13,40 @@ package com.jz.dmp.modules.service;
* @Version 1.0 * @Version 1.0
*/ */
public interface DmpOrgMangeService { public interface DmpOrgMangeService {
/**
* 列表分页查询
*
* @return
* @author Bellamy
* @since 2021-01-16
*/
JsonResult queryOrgListPage(OrganizationManageListQueryReq req) throws Exception;
/**
* 删除组织
*
* @return
* @author Bellamy
* @since 2021-01-16
*/
JsonResult delOrgById(long id) throws Exception;
/**
* 新增组织
*
* @return
* @author Bellamy
* @since 2021-01-16
*/
JsonResult addOrg(OrganizationManageAddReq req) throws Exception;
/**
* 编辑组织
*
* @return
* @author Bellamy
* @since 2021-01-16
*/
JsonResult updateOrg(OrganizationManageUpdateReq req) throws Exception;
} }
package com.jz.dmp.modules.service.impl; package com.jz.dmp.modules.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.jz.common.constant.JsonResult;
import com.jz.common.utils.web.HttpClientUtils;
import com.jz.dmp.modules.controller.dataService.bean.OrganizationManageAddReq;
import com.jz.dmp.modules.controller.dataService.bean.OrganizationManageListQueryReq;
import com.jz.dmp.modules.controller.dataService.bean.OrganizationManageUpdateReq;
import com.jz.dmp.modules.service.DmpOrgMangeService; import com.jz.dmp.modules.service.DmpOrgMangeService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** /**
* @ClassName: DmpOrgMangeServiceImpl * @ClassName: DmpOrgMangeServiceImpl
* @Description: 数据服务组织管理 * @Description: 数据服务组织管理
...@@ -13,5 +27,119 @@ import org.springframework.stereotype.Service; ...@@ -13,5 +27,119 @@ import org.springframework.stereotype.Service;
@Service("dmpOrgMangeService") @Service("dmpOrgMangeService")
public class DmpOrgMangeServiceImpl implements DmpOrgMangeService { public class DmpOrgMangeServiceImpl implements DmpOrgMangeService {
private static Logger logger = LoggerFactory.getLogger(DmpOrgMangeServiceImpl.class);
//列表分页查询url
private static final String orgListPage = "/api/organization/listOrg";
//删除组织url
private static final String delOrg = "/api/organization/logoutOrg";
//新增组织url
private static final String addOrg = "/api/organization/add";
//编辑组织url
private static final String updateOrg = "/api/organization/update";
@Value("${spring.gateway-url}")
private String gatewayUrl;
/**
* 列表分页查询
*
* @return
* @author Bellamy
* @since 2021-01-16
*/
@Override
public JsonResult queryOrgListPage(OrganizationManageListQueryReq req) throws Exception {
JsonResult result = new JsonResult();
String url = gatewayUrl + orgListPage;
if (StringUtils.isNotEmpty(req.getOrgName())) {
req.setOrgName(req.getOrgName().trim());
}
String resultData = HttpClientUtils.post(url, JSONObject.toJSONString(req));
if (StringUtils.isEmpty(resultData)) {
throw new RuntimeException("查询失败!");
}
logger.info("#################组织管理列数据{}" + resultData);
Map jsonObject = JSONObject.parseObject(resultData);
if (jsonObject != null) {
result.setData(jsonObject.get("data"));
/*Map records = JSONObject.parseObject(jsonObject.get("data").toString());
List<Map> list = (List<Map>) records.get("records");*/
}
return result;
}
/**
* 删除组织
*
* @return
* @author Bellamy
* @since 2021-01-16
*/
@Override
public JsonResult delOrgById(long id) throws Exception {
Map params = new HashMap();
params.put("id", id);
String url = gatewayUrl + delOrg;
String returnData = HttpClientUtils.getJsonForParam(url, params);
if (StringUtils.isEmpty(returnData)) {
throw new RuntimeException("删除失败!");
}
logger.info("#################响应结果{}" + returnData);
Map map = JSONObject.parseObject(returnData);
if ("200".equals(map.get("code").toString())) {
return JsonResult.ok();
}
return JsonResult.error("删除失败!");
}
/**
* 新增组织
*
* @return
* @author Bellamy
* @since 2021-01-16
*/
@Override
public JsonResult addOrg(OrganizationManageAddReq req) throws Exception {
String url = gatewayUrl + addOrg;
String returnData = HttpClientUtils.post(url, JSONObject.toJSONString(req));
if (StringUtils.isEmpty(returnData)) {
throw new RuntimeException("新增失败!");
}
logger.info("#################响应结果{}" + returnData);
Map map = JSONObject.parseObject(returnData);
if ("200".equals(map.get("code").toString())) {
return JsonResult.ok();
}
logger.info(map.get("message").toString());
return JsonResult.error(map.get("message").toString());
}
/**
* 编辑组织
*
* @return
* @author Bellamy
* @since 2021-01-16
*/
@Override
public JsonResult updateOrg(OrganizationManageUpdateReq req) throws Exception {
String url = gatewayUrl + updateOrg;
String returnData = HttpClientUtils.post(url, JSONObject.toJSONString(req));
if (StringUtils.isEmpty(returnData)) {
throw new RuntimeException("编辑失败!");
}
logger.info("#################响应结果{}" + returnData);
Map map = JSONObject.parseObject(returnData);
if ("200".equals(map.get("code").toString())) {
return JsonResult.ok();
}
logger.info(map.get("message").toString());
return JsonResult.error(map.get("message").toString());
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment