Commit d6f0806e hjh

富士接口代码提交

1 个父辈 aa41a5d9
...@@ -39,287 +39,353 @@ import java.util.Map.Entry; ...@@ -39,287 +39,353 @@ import java.util.Map.Entry;
*/ */
@Slf4j @Slf4j
public class HttpHelper { public class HttpHelper {
// 编码方式 // 编码方式
private static final String CONTENT_CHARSET = "UTF-8"; private static final String CONTENT_CHARSET = "UTF-8";
// 连接超时时间 // 连接超时时间
private static final int CONNECTION_TIMEOUT = 10000; private static final int CONNECTION_TIMEOUT = 10000;
// 读数据超时时间 // 读数据超时时间
private static final int READ_DATA_TIMEOUT = 10000; private static final int READ_DATA_TIMEOUT = 10000;
/** /**
* 兼容smdBox接口 * 兼容smdBox接口
* @param url *
* @param paramMap * @param url
* @param user * @param paramMap
* @param pwd * @param user
* @return * @param pwd
* @throws ApiException * @return
*/ * @throws ApiException
@Deprecated */
public static String postParamWithAuth(String url, Map<String, Object> paramMap, String user, String pwd) throws ApiException { @Deprecated
PrintWriter out = null; public static String postParamWithAuth(String url, Map<String, Object> paramMap, String user, String pwd) throws ApiException {
BufferedReader in = null; PrintWriter out = null;
String result = ""; BufferedReader in = null;
try { String result = "";
URL realUrl = new URL(url); try {
// 打开和URL之间的连接 URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection(); // 打开和URL之间的连接
// 设置通用的请求属性 URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*"); // 设置通用的请求属性
conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//设置用户名和密码
//设置用户名和密码
if (Strings.isNotBlank(user)) {
String auth = user + ":" + pwd; if (Strings.isNotBlank(user)) {
//对其进行加密 String auth = user + ":" + pwd;
byte[] rel = Base64.getEncoder().encode(auth.getBytes()); //对其进行加密
String res = new String(rel); byte[] rel = Base64.getEncoder().encode(auth.getBytes());
//设置认证属性 String res = new String(rel);
conn.setRequestProperty("Authorization", "Basic " + res); //设置认证属性
} conn.setRequestProperty("Authorization", "Basic " + res);
}
// conn.setRequestProperty("Charset", "UTF-8");
// 发送POST请求必须设置如下两行 // conn.setRequestProperty("Charset", "UTF-8");
conn.setDoOutput(true); // 发送POST请求必须设置如下两行
conn.setDoInput(true); conn.setDoOutput(true);
// 获取URLConnection对象对应的输出流 conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream()); // 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 设置请求属性
String param = ""; // 设置请求属性
if (paramMap != null && paramMap.size() > 0) { String param = "";
Iterator<String> ite = paramMap.keySet().iterator(); if (paramMap != null && paramMap.size() > 0) {
while (ite.hasNext()) { Iterator<String> ite = paramMap.keySet().iterator();
String key = ite.next();// key while (ite.hasNext()) {
Object valueObj = paramMap.get(key); String key = ite.next();// key
String value = ""; Object valueObj = paramMap.get(key);
if (valueObj != null) { String value = "";
if (valueObj instanceof Date) { if (valueObj != null) {
DateUtil.toDateString((Date) valueObj, "yyyyMMdd"); if (valueObj instanceof Date) {
} else { DateUtil.toDateString((Date) valueObj, "yyyyMMdd");
value = valueObj.toString(); } else {
} value = valueObj.toString();
} }
param += key + "=" + value + "&"; }
} param += key + "=" + value + "&";
param = param.substring(0, param.length() - 1); }
} param = param.substring(0, param.length() - 1);
}
// 发送请求参数
out.print(param); // 发送请求参数
// flush输出流的缓冲 out.print(param);
out.flush(); // flush输出流的缓冲
// 定义BufferedReader输入流来读取URL的响应 out.flush();
in = new BufferedReader( // 定义BufferedReader输入流来读取URL的响应
new InputStreamReader(conn.getInputStream())); in = new BufferedReader(
String line; new InputStreamReader(conn.getInputStream()));
while ((line = in.readLine()) != null) { String line;
result += line; while ((line = in.readLine()) != null) {
} result += line;
} catch (Exception e) { }
throw new ApiException("Request [" + url + "] failed:" + e.getMessage()); } catch (Exception e) {
} throw new ApiException("Request [" + url + "] failed:" + e.getMessage());
// 使用finally块来关闭输出流、输入流 }
finally { // 使用finally块来关闭输出流、输入流
try { finally {
if (out != null) { try {
out.close(); if (out != null) {
} out.close();
if (in != null) { }
in.close(); if (in != null) {
} in.close();
} catch (IOException ex) { }
throw new ApiException("Request [" + url + "] close instream failed:" + ex.getMessage()); } catch (IOException ex) {
} throw new ApiException("Request [" + url + "] close instream failed:" + ex.getMessage());
} }
return result; }
} return result;
}
public static String postJson(String url, Map<String, Object> params) throws ApiException {
// 设置请求参数 public static String postJson(String url, Map<String, Object> params) throws ApiException {
if (params == null || params.isEmpty()) { // 设置请求参数
params = null; if (params == null || params.isEmpty()) {
} params = null;
return postJsonWithAuth(url, params, null); }
} return postJsonWithAuth(url, params, null);
}
public static String postJsonWithAuth(String url, Object params, String auth) throws ApiException { public static String postJsonWithAuth(String url, Object params, String auth) throws ApiException {
String requestBody = ""; String requestBody = "";
// 设置请求参数 // 设置请求参数
if (params != null) { if (params != null) {
try { try {
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
requestBody = mapper.writeValueAsString(params); requestBody = mapper.writeValueAsString(params);
} catch (JsonProcessingException e) { } catch (JsonProcessingException e) {
throw new ApiException("Request params to [" + url + "] Json failed:" + e.getMessage()); throw new ApiException("Request params to [" + url + "] Json failed:" + e.getMessage());
} catch (Exception e) { } catch (Exception e) {
throw new ApiException("Request params to [" + url + "] json exception:" + e.getMessage()); throw new ApiException("Request params to [" + url + "] json exception:" + e.getMessage());
} }
} }
HttpPost httpPost = null; HttpPost httpPost = null;
CloseableHttpClient httpClient = null; CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null; CloseableHttpResponse response = null;
try { try {
httpPost = new HttpPost(url); httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json;charset=utf-8"); httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
if (auth != null && !auth.isEmpty()) { if (auth != null && !auth.isEmpty()) {
httpPost.addHeader("Authorization", auth); httpPost.addHeader("Authorization", auth);
} }
httpPost.setEntity(new StringEntity(requestBody, CONTENT_CHARSET)); httpPost.setEntity(new StringEntity(requestBody, CONTENT_CHARSET));
httpClient = HttpClients.createDefault(); httpClient = HttpClients.createDefault();
response = httpClient.execute(httpPost); response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity(); HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET); String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET);
//response.close(); //response.close();
//httpClient.close(); //httpClient.close();
return responseContent; return responseContent;
} catch (Exception e) { } catch (Exception e) {
throw new ApiException("Request to [" + url + "]["+requestBody+"] failed:" + e.getMessage()); throw new ApiException("Request to [" + url + "][" + requestBody + "] failed:" + e.getMessage());
} finally { } finally {
try { try {
if (response != null) { if (response != null) {
response.close(); response.close();
} }
if (httpClient != null) { if (httpClient != null) {
httpClient.close(); httpClient.close();
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
if (httpPost != null) { if (httpPost != null) {
httpPost.releaseConnection(); httpPost.releaseConnection();
} }
} }
} }
/** public static String postJson(String url, Map<String, Object> params, Map<String, String> headerMap) throws ApiException {
* 向指定URL发送POST请求 // 设置请求参数
* @param url if (params == null || params.isEmpty()) {
* @param paramMap params = null;
* @return 响应结果 }
*/ return postJsonWithAuth(url, params, null, headerMap);
public static String postParam(String url, Map<String, Object> paramMap) throws ApiException { }
String contentType = "application/json;charset=utf-8";
return postParam(url, paramMap, contentType); public static String postJsonWithAuth(String url, Object params, String auth, Map<String, String> headerMap) throws ApiException {
}
String requestBody = "";
public static String postFormParam(String url, Map<String, Object> paramMap) throws ApiException { // 设置请求参数
String contentType = "application/x-www-form-urlencoded"; if (params != null) {
return postParam(url, paramMap, contentType); try {
} ObjectMapper mapper = new ObjectMapper();
requestBody = mapper.writeValueAsString(params);
public static String postParam(String url, Map<String, Object> paramMap, String contentType) throws ApiException { } catch (JsonProcessingException e) {
// 设置请求参数 throw new ApiException("Request params to [" + url + "] Json failed:" + e.getMessage());
CloseableHttpClient httpClient = null; } catch (Exception e) {
CloseableHttpResponse response = null; throw new ApiException("Request params to [" + url + "] json exception:" + e.getMessage());
HttpPost httpPost = null; }
try { }
List<NameValuePair> params = toNameValuePair(paramMap);
URI uri = new URIBuilder(url).setParameters(params).build(); HttpPost httpPost = null;
log.info("执行请求:" + uri.toString()); CloseableHttpClient httpClient = null;
httpPost = new HttpPost(uri); CloseableHttpResponse response = null;
httpPost.addHeader("Content-Type", contentType); try {
httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
if (headerMap != null && !headerMap.isEmpty()) {
for (Entry<String, String> entry : headerMap.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
}
if (auth != null && !auth.isEmpty()) {
httpPost.addHeader("Authorization", auth);
}
httpPost.setEntity(new StringEntity(requestBody, CONTENT_CHARSET));
httpClient = HttpClients.createDefault();
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET);
//response.close();
//httpClient.close();
return responseContent;
} catch (Exception e) {
throw new ApiException("Request to [" + url + "][" + requestBody + "] failed:" + e.getMessage());
} finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (httpPost != null) {
httpPost.releaseConnection();
}
}
}
/**
* 向指定URL发送POST请求
*
* @param url
* @param paramMap
* @return 响应结果
*/
public static String postParam(String url, Map<String, Object> paramMap) throws ApiException {
String contentType = "application/json;charset=utf-8";
return postParam(url, paramMap, contentType);
}
public static String postFormParam(String url, Map<String, Object> paramMap) throws ApiException {
String contentType = "application/x-www-form-urlencoded";
return postParam(url, paramMap, contentType);
}
public static String postParam(String url, Map<String, Object> paramMap, String contentType) throws ApiException {
// 设置请求参数
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpPost httpPost = null;
try {
List<NameValuePair> params = toNameValuePair(paramMap);
URI uri = new URIBuilder(url).setParameters(params).build();
log.info("执行请求:" + uri.toString());
httpPost = new HttpPost(uri);
httpPost.addHeader("Content-Type", contentType);
// httpPost.setEntity(new UrlEncodedFormEntity(params, CONTENT_CHARSET)); // httpPost.setEntity(new UrlEncodedFormEntity(params, CONTENT_CHARSET));
httpClient = HttpClients.createDefault(); httpClient = HttpClients.createDefault();
response = httpClient.execute(httpPost); response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity(); HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET); String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET);
//response.close(); //response.close();
//httpClient.close(); //httpClient.close();
return responseContent; return responseContent;
} catch (Exception e) { } catch (Exception e) {
throw new ApiException("Request params to [" + url + "] failed:" + e.getMessage()); throw new ApiException("Request params to [" + url + "] failed:" + e.getMessage());
}finally { } finally {
try { try {
if (response != null) { if (response != null) {
response.close(); response.close();
} }
if (httpClient != null) { if (httpClient != null) {
httpClient.close(); httpClient.close();
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
if (httpPost != null){ if (httpPost != null) {
httpPost.releaseConnection(); httpPost.releaseConnection();
} }
} }
} }
private static List<NameValuePair> toNameValuePair(Map<String, Object> paramMap) { private static List<NameValuePair> toNameValuePair(Map<String, Object> paramMap) {
List<NameValuePair> params = new ArrayList<NameValuePair>(); List<NameValuePair> params = new ArrayList<NameValuePair>();
if (paramMap != null && !paramMap.isEmpty()) { if (paramMap != null && !paramMap.isEmpty()) {
//建立一个NameValuePair数组,用于存储欲传送的参数 //建立一个NameValuePair数组,用于存储欲传送的参数
for (Entry<String, Object> entry : paramMap.entrySet()) { for (Entry<String, Object> entry : paramMap.entrySet()) {
String value = ""; String value = "";
Object valueObj = entry.getValue(); Object valueObj = entry.getValue();
if (valueObj != null) { if (valueObj != null) {
if (valueObj instanceof Date) { if (valueObj instanceof Date) {
value = DateUtil.toDateString((Date) valueObj, "yyyyMMdd"); value = DateUtil.toDateString((Date) valueObj, "yyyyMMdd");
} else { } else {
value = valueObj.toString(); value = valueObj.toString();
} }
} }
params.add(new BasicNameValuePair(entry.getKey(), value)); params.add(new BasicNameValuePair(entry.getKey(), value));
} }
} }
return params; return params;
} }
public static String posJsonParams(String url, Object params) throws ApiException { public static String posJsonParams(String url, Object params) throws ApiException {
HttpPost httpPost = new HttpPost(url); HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json;charset=utf-8"); httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
// 设置请求参数 // 设置请求参数
if (params != null) { if (params != null) {
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
try { try {
String requestBody = mapper.writeValueAsString(params); String requestBody = mapper.writeValueAsString(params);
httpPost.setEntity(new StringEntity(requestBody, CONTENT_CHARSET)); httpPost.setEntity(new StringEntity(requestBody, CONTENT_CHARSET));
} catch (JsonProcessingException e) { } catch (JsonProcessingException e) {
throw new ApiException("Request params to [" + url + "] Json failed:" + e.getMessage()); throw new ApiException("Request params to [" + url + "] Json failed:" + e.getMessage());
} catch (Exception e) { } catch (Exception e) {
throw new ApiException("Request params to [" + url + "] json exception:" + e.getMessage()); throw new ApiException("Request params to [" + url + "] json exception:" + e.getMessage());
} }
} }
CloseableHttpClient httpClient = null; CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null; CloseableHttpResponse response = null;
try { try {
httpClient = HttpClients.createDefault(); httpClient = HttpClients.createDefault();
response = httpClient.execute(httpPost); response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity(); HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET); String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET);
//response.close(); //response.close();
//httpClient.close(); //httpClient.close();
return responseContent; return responseContent;
} catch (Exception e) { } catch (Exception e) {
throw new ApiException("Request to [" + url + "] failed:" + e.getMessage()); throw new ApiException("Request to [" + url + "] failed:" + e.getMessage());
}finally { } finally {
try { try {
if (response != null) { if (response != null) {
response.close(); response.close();
} }
if (httpClient != null) { if (httpClient != null) {
httpClient.close(); httpClient.close();
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
public static MicronResult getMicronJson(String url) throws ApiException { public static MicronResult getMicronJson(String url) throws ApiException {
if (ObjectUtil.isEmpty(url)) { if (ObjectUtil.isEmpty(url)) {
return new MicronResult(); return new MicronResult();
} }
HttpGet httpGet = new HttpGet(url); HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Content-Type", "application/json;charset=utf-8"); httpGet.addHeader("Content-Type", "application/json;charset=utf-8");
// // 设置请求参数 // // 设置请求参数
// if (params != null && !params.isEmpty()) { // if (params != null && !params.isEmpty()) {
// ObjectMapper mapper = new ObjectMapper(); // ObjectMapper mapper = new ObjectMapper();
...@@ -332,205 +398,205 @@ public class HttpHelper { ...@@ -332,205 +398,205 @@ public class HttpHelper {
// throw new ApiException("Request params to [" + url + "] failed:" + e.getMessage()); // throw new ApiException("Request params to [" + url + "] failed:" + e.getMessage());
// } // }
// } // }
CloseableHttpClient httpClient = null; CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null; CloseableHttpResponse response = null;
try { try {
httpClient = HttpClients.createDefault(); httpClient = HttpClients.createDefault();
response = httpClient.execute(httpGet); response = httpClient.execute(httpGet);
int code = response.getStatusLine().getStatusCode(); int code = response.getStatusLine().getStatusCode();
//System.out.println(response.getStatusLine().getStatusCode() + "\n"); //System.out.println(response.getStatusLine().getStatusCode() + "\n");
HttpEntity entity = response.getEntity(); HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET); String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET);
MicronResult result = JsonUtil.toObj(responseContent, MicronResult.class); MicronResult result = JsonUtil.toObj(responseContent, MicronResult.class);
if (result == null) { if (result == null) {
result = new MicronResult(); result = new MicronResult();
} }
result.setHttpCode(code); result.setHttpCode(code);
result.setResponseData(responseContent); result.setResponseData(responseContent);
//response.close(); //response.close();
//httpClient.close(); //httpClient.close();
return result; return result;
} catch (Exception e) { } catch (Exception e) {
throw new ApiException("Request to [" + url + "] failed:" + e.getMessage()); throw new ApiException("Request to [" + url + "] failed:" + e.getMessage());
}finally { } finally {
try { try {
if (response != null) { if (response != null) {
response.close(); response.close();
} }
if (httpClient != null) { if (httpClient != null) {
httpClient.close(); httpClient.close();
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
public static MicronResult postMicronJson(String url, Map<String, Object> params) throws ApiException { public static MicronResult postMicronJson(String url, Map<String, Object> params) throws ApiException {
try { try {
if (ObjectUtil.isEmpty(url)) { if (ObjectUtil.isEmpty(url)) {
return new MicronResult(); return new MicronResult();
} }
String responseContent = postJson(url, params); String responseContent = postJson(url, params);
MicronResult result = JsonUtil.toObj(responseContent, MicronResult.class); MicronResult result = JsonUtil.toObj(responseContent, MicronResult.class);
if (result == null) { if (result == null) {
result = new MicronResult(); result = new MicronResult();
} }
result.setResponseData(responseContent); result.setResponseData(responseContent);
return result; return result;
} catch (Exception e) { } catch (Exception e) {
throw new ApiException("Request to [" + url + "] failed:" + e.getMessage()); throw new ApiException("Request to [" + url + "] failed:" + e.getMessage());
} }
} }
public static String getJson(String url, Object params) throws ApiException { public static String getJson(String url, Object params) throws ApiException {
// 设置请求参数 // 设置请求参数
if (params != null) { if (params != null) {
try { try {
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
String requestBody = mapper.writeValueAsString(params); String requestBody = mapper.writeValueAsString(params);
List<NameValuePair> nameValuePairs = new LinkedList<>(); List<NameValuePair> nameValuePairs = new LinkedList<>();
nameValuePairs.add(new BasicNameValuePair("JSON", requestBody)); nameValuePairs.add(new BasicNameValuePair("JSON", requestBody));
String paramStr = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs)); String paramStr = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs));
url = appendString(url, paramStr); url = appendString(url, paramStr);
// url=url+"?JSON="+requestBody; // url=url+"?JSON="+requestBody;
} catch (Exception e) { } catch (Exception e) {
throw new ApiException("getJson append params to [" + url + "] exception:" + e.getMessage()); throw new ApiException("getJson append params to [" + url + "] exception:" + e.getMessage());
} }
} }
CloseableHttpClient httpClient = null; CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null; CloseableHttpResponse response = null;
try { try {
HttpGet httpGet = new HttpGet(url); HttpGet httpGet = new HttpGet(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT).build(); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT).build();
httpGet.setConfig(requestConfig); httpGet.setConfig(requestConfig);
httpGet.addHeader("Content-Type", "application/json;charset=utf-8"); httpGet.addHeader("Content-Type", "application/json;charset=utf-8");
httpClient = HttpClients.createDefault(); httpClient = HttpClients.createDefault();
response = httpClient.execute(httpGet); response = httpClient.execute(httpGet);
int code = response.getStatusLine().getStatusCode(); int code = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity(); HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET); String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET);
//response.close(); //response.close();
//httpClient.close(); //httpClient.close();
return responseContent; return responseContent;
} catch (Exception e) { } catch (Exception e) {
throw new ApiException("Request to [" + url + "] failed:" + e.getMessage()); throw new ApiException("Request to [" + url + "] failed:" + e.getMessage());
}finally { } finally {
try { try {
if (response != null) { if (response != null) {
response.close(); response.close();
} }
if (httpClient != null) { if (httpClient != null) {
httpClient.close(); httpClient.close();
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
public static String getJson(String url,Map<String,String> headerMap ,Object params) throws ApiException { public static String getJson(String url, Map<String, String> headerMap, Object params) throws ApiException {
// 设置请求参数 // 设置请求参数
if (params != null) { if (params != null) {
try { try {
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
String requestBody = mapper.writeValueAsString(params); String requestBody = mapper.writeValueAsString(params);
List<NameValuePair> nameValuePairs = new LinkedList<>(); List<NameValuePair> nameValuePairs = new LinkedList<>();
nameValuePairs.add(new BasicNameValuePair("JSON", requestBody)); nameValuePairs.add(new BasicNameValuePair("JSON", requestBody));
String paramStr = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs)); String paramStr = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs));
url = appendString(url, paramStr); url = appendString(url, paramStr);
// url=url+"?JSON="+requestBody; // url=url+"?JSON="+requestBody;
} catch (Exception e) { } catch (Exception e) {
throw new ApiException("getJson append params to [" + url + "] exception:" + e.getMessage()); throw new ApiException("getJson append params to [" + url + "] exception:" + e.getMessage());
} }
} }
CloseableHttpClient httpClient = null; CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null; CloseableHttpResponse response = null;
try { try {
HttpGet httpGet = new HttpGet(url); HttpGet httpGet = new HttpGet(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT).build(); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT).build();
httpGet.setConfig(requestConfig); httpGet.setConfig(requestConfig);
if (headerMap != null && !headerMap.isEmpty()) { if (headerMap != null && !headerMap.isEmpty()) {
for (Entry<String, String> entry : headerMap.entrySet()) { for (Entry<String, String> entry : headerMap.entrySet()) {
httpGet.addHeader(entry.getKey(), entry.getValue()); httpGet.addHeader(entry.getKey(), entry.getValue());
} }
} }
httpClient = HttpClients.createDefault(); httpClient = HttpClients.createDefault();
response = httpClient.execute(httpGet); response = httpClient.execute(httpGet);
int code = response.getStatusLine().getStatusCode(); int code = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity(); HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET); String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET);
//response.close(); //response.close();
//httpClient.close(); //httpClient.close();
return responseContent; return responseContent;
} catch (Exception e) { } catch (Exception e) {
throw new ApiException("Request to [" + url + "] failed:" + e.getMessage()); throw new ApiException("Request to [" + url + "] failed:" + e.getMessage());
}finally { } finally {
try { try {
if (response != null) { if (response != null) {
response.close(); response.close();
} }
if (httpClient != null) { if (httpClient != null) {
httpClient.close(); httpClient.close();
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
public static String postParam(String url, Map<String, Object> paramMap, Map<String,String> headerMap) throws ApiException { public static String postParam(String url, Map<String, Object> paramMap, Map<String, String> headerMap) throws ApiException {
// 设置请求参数 // 设置请求参数
CloseableHttpClient httpClient = null; CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null; CloseableHttpResponse response = null;
try { try {
List<NameValuePair> params = toNameValuePair(paramMap); List<NameValuePair> params = toNameValuePair(paramMap);
URI uri = new URIBuilder(url).setParameters(params).build(); URI uri = new URIBuilder(url).setParameters(params).build();
log.info("执行请求:" + uri.toString()); log.info("执行请求:" + uri.toString());
HttpPost httpPost = new HttpPost(uri); HttpPost httpPost = new HttpPost(uri);
for (Entry<String, String> entry : headerMap.entrySet()) { for (Entry<String, String> entry : headerMap.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue()); httpPost.addHeader(entry.getKey(), entry.getValue());
} }
// httpPost.setEntity(new UrlEncodedFormEntity(params, CONTENT_CHARSET)); // httpPost.setEntity(new UrlEncodedFormEntity(params, CONTENT_CHARSET));
httpClient = HttpClients.createDefault(); httpClient = HttpClients.createDefault();
response = httpClient.execute(httpPost); response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity(); HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET); String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET);
//response.close(); //response.close();
//httpClient.close(); //httpClient.close();
return responseContent; return responseContent;
} catch (Exception e) { } catch (Exception e) {
throw new ApiException("Request params to [" + url + "] failed:" + e.getMessage()); throw new ApiException("Request params to [" + url + "] failed:" + e.getMessage());
}finally { } finally {
try { try {
if (response != null) { if (response != null) {
response.close(); response.close();
} }
if (httpClient != null) { if (httpClient != null) {
httpClient.close(); httpClient.close();
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
private static String appendString(String url, String paramStr) { private static String appendString(String url, String paramStr) {
StringBuffer stringBuffer = new StringBuffer(); StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(url); stringBuffer.append(url);
stringBuffer.append("?"); stringBuffer.append("?");
stringBuffer.append(paramStr); stringBuffer.append(paramStr);
return stringBuffer.toString(); return stringBuffer.toString();
} }
} }
package com.neotel.smfcore.custom.fushi;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.neotel.smfcore.common.utils.HttpHelper;
import com.neotel.smfcore.core.api.listener.DefaultSmfApiListener;
import com.neotel.smfcore.custom.fushi.bean.FushiApiToken;
import com.neotel.smfcore.custom.fushi.bean.InventoryDid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
@Slf4j
public class FuShiApi extends DefaultSmfApiListener {
@Value("${smd.userName}")
private String userName;
@Value("${smd.password}")
private String password;
@Value("${smd.url}")
private String fuShiUrl;
public static final String tokenUrl = "auth/login";
public static final String inventoryUrl = "inventory/dids";
private String accessToken;
public String getAccessToken() {
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("userName", userName);
paramMap.put("password", password);
log.info("getAccessToken调用参数为:" + JSON.toJSONString(paramMap));
String result = "";
try {
String url = fuShiUrl + tokenUrl;
result = HttpHelper.postJson(url, paramMap);
// result = "{\n" +
// " \"accessToken\": \"accessToken1234\",\n" +
// " \"refreshToken\": \"refreshToken12345\"\n" +
// "}";
log.info("getAccessToken接口返回为:" + result);
FushiApiToken fushiApiToken = JSONObject.parseObject(result, FushiApiToken.class);
result = fushiApiToken.getAccess_token();
accessToken = fushiApiToken.getAccess_token();
} catch (Exception e) {
e.printStackTrace();
log.info("getAccessToken接口错误信息为:" + e.getMessage());
}
return result;
}
public List<String> getInventoryList(int pageSize, int pageToken) {
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("pageSize", pageSize);
paramMap.put("pageToken", pageToken);
log.info("getInventoryList调用参数为:" + JSON.toJSONString(paramMap));
List<String> inventoryDids = new ArrayList<>();
String result = "";
try {
String url = fuShiUrl + inventoryUrl;
HashMap<String, String> headerMap = new HashMap<>();
headerMap.put("fujiAccessToken", accessToken);
result = HttpHelper.getJson(url,headerMap, paramMap);
// result = "{\n" +
// " \"datas\": [\n" +
// " {\n" +
// " \"did\": \"121\",\n" +
// " \"partNumber\": \"M21000012\",\n" +
// " \"quantity\": 21234\n" +
// " },\n" +
// " {\n" +
// " \"did\": \"12345\",\n" +
// " \"partNumber\": \"M21230012\",\n" +
// " \"quantity\": 16394\n" +
// " },\n" +
// " {\n" +
// " \"did\": \"1223\",\n" +
// " \"partNumber\": \"M21000232\",\n" +
// " \"quantity\": 16734\n" +
// " }\n" +
// " ],\n" +
// " \"metadata\": {\n" +
// " \"totalCount\": 14,\n" +
// " \"pageSize\": 0\n" +
// " }\n" +
// "}";
log.info("getInventoryList接口返回为:" + result);
InventoryDid inventory = JSONObject.parseObject(result, InventoryDid.class);
if (inventory != null) {
if (inventory.getDatas() != null && !inventory.getDatas().isEmpty()) {
for (int i = 0; i < inventory.getDatas().size(); i++) {
String did = inventory.getDatas().get(i).getDid();
inventoryDids.add(did);
}
}
}
} catch (Exception e) {
e.printStackTrace();
log.info("getInventoryList接口错误信息为:" + e.getMessage());
}
return inventoryDids;
}
public String getInventoryAdd(String partBarcode, Integer quantity, String partNumber) {
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("partBarcode", partBarcode);
paramMap.put("quantity", quantity);
paramMap.put("partNumber", partNumber);
log.info("getInventoryAdd调用参数为:" + JSON.toJSONString(paramMap));
String result = "";
try {
String url = fuShiUrl + inventoryUrl;
HashMap<String, String> headerMap = new HashMap<>();
headerMap.put("fujiAccessToken", accessToken);
result = HttpHelper.postJson(url, paramMap, headerMap);
// result = "{\n" +
// " \"addedCount\": 100\n" +
// "}";
log.info("getInventoryAdd接口返回为:" + result);
InventoryDid ResultData = JSONObject.parseObject(result, InventoryDid.class);
Integer addedCount = ResultData.getAddedCount();
result = addedCount + "";
} catch (Exception e) {
e.printStackTrace();
log.info("getInventoryAdd接口错误信息为:" + e.getMessage());
}
return result;
}
}
package com.neotel.smfcore.custom.fushi.bean;
import lombok.Data;
@Data
public class FushiApiToken {
private String access_token;
private String refresh_token;
}
package com.neotel.smfcore.custom.fushi.bean.Inventory;
import lombok.Data;
@Data
public class Datas {
private String did;
private String partNumber;
private String partBarcode;
private String originalPartBarcode;
private Integer quantity;
private String packageType;
private Integer partsoutWarning;
private Integer splicingWarning;
private String vendorName;
private String lotName;
private String dateCode;
private String area;
private String location;
private String machine;
private Integer module;
private Integer stageNo;
private Integer slotNo;
private String createdUser;
private String createDate;
private String updatedUser;
private String updatedDate;
private String dryStatus;
private String boxLife;
private String floorLife;
private String memo;
private String lightingClass;
private Integer lightingLimit;
private String note1;
private String note2;
private String note3;
private String note4;
private boolean useSplicing;
private boolean useTrayPackage;
private Integer trayStackCount;
private Integer trayPickupPositionX;
private Integer trayPickupPositionY;
private Integer traySizeX;
private Integer traySizeY;
}
package com.neotel.smfcore.custom.fushi.bean.Inventory;
import lombok.Data;
@Data
public class MetaData {
private Integer totalCount;
private Integer pageSize;
private Integer pageToken;
private String nextPageToken;
}
package com.neotel.smfcore.custom.fushi.bean;
import com.neotel.smfcore.custom.fushi.bean.Inventory.Datas;
import com.neotel.smfcore.custom.fushi.bean.Inventory.MetaData;
import lombok.Data;
import java.util.List;
@Data
public class InventoryDid {
private List<Datas> datas;
private MetaData metadata;
private Integer addedCount;
}
package com.neotel.smfcore.custom.fushi.controller;
import com.neotel.smfcore.common.bean.ResultBean;
import com.neotel.smfcore.core.barcode.service.po.Barcode;
import com.neotel.smfcore.custom.fushi.FuShiApi;
import com.neotel.smfcore.custom.fushi.bean.InventoryDid;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.HttpPost;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@Api(tags = "fuShi接口")
@Slf4j
@RestController
@RequestMapping("/manuallyPutStorage")
public class ManuallyPutStorageController {
@Autowired
private FuShiApi fuShiApi;
/***
*
* @param barcode
* @param did
*/
@RequestMapping("/PutInStorage")
public ResultBean PutInStorage(@RequestBody Barcode barcode, @RequestParam String did) {
log.info("调用接口PutInStorage用到的参数:" + barcode + " DiD为" + did);
String accessToken = fuShiApi.getAccessToken();
if (accessToken.isEmpty()) {
log.error("调用接口getAccessToken异常");
return ResultBean.newErrorResult(-1, "", "调用接口getAccessToken信息错误,数据为空");
}
Integer pageSize = 12;
Integer pageToken = 0;
List<String> inventoryList = fuShiApi.getInventoryList(pageSize, pageToken);
if (inventoryList == null || inventoryList.size() == 0) {
log.error("调用接口getInventoryList异常");
return ResultBean.newErrorResult(-1, "", "调用接口getInventoryList信息错误,数据为空");
}
boolean inFlag = true;
for (int i = 0; i < inventoryList.size(); i++) {
String inDid = inventoryList.get(i);
if (did.equals(inDid)) {
inFlag = false;
break;
}
}
if (inFlag) {
String partBarcode = barcode.getBarcode();
Integer quantity = barcode.getAmount();
String partNumber = barcode.getPartNumber();
String inventoryAdd = fuShiApi.getInventoryAdd(partBarcode, quantity, partNumber);
if ("".equals(inventoryAdd)) {
log.error("调用接口getInventoryAdd异常");
return ResultBean.newErrorResult(-1, "", "调用getInventoryAdd接口信息错误,数据为空");
}
}
return ResultBean.newOkResult("OK");
}
}
...@@ -12,18 +12,18 @@ spring: ...@@ -12,18 +12,18 @@ spring:
host: localhost # 主机地址 host: localhost # 主机地址
port: 27017 # 端口 port: 27017 # 端口
database: smf # 数据库 database: smf # 数据库
username: username: Siemens
password: password: Siemens
#备份数据库,如果有,则开启,注意:如果主数据库设置了用户名和密码,备份服务器必须设置用户名和密码!! #备份数据库,如果有,则开启,注意:如果主数据库设置了用户名和密码,备份服务器必须设置用户名和密码!!
#西门子的正式和备份数据库,用户名和密码都是Siemens #西门子的正式和备份数据库,用户名和密码都是Siemens
#backup-mongodb: backup-mongodb:
# auto-index-creation: true # 默认为false,即不会自动创建索引 auto-index-creation: true # 默认为false,即不会自动创建索引
# host: localhost # 主机地址 host: localhost # 主机地址
# port: 27017 # 端口 port: 27017 # 端口
# database: backup_smf # 数据库 database: backup_smf # 数据库
# username: username: Siemens
# password: password: Siemens
servlet: servlet:
multipart: multipart:
......
...@@ -7,6 +7,8 @@ api: ...@@ -7,6 +7,8 @@ api:
outNotifyUrl: outNotifyUrl:
inNotifyUrl: inNotifyUrl:
hella: hella:
#host: 127.0.0.1 #host: 127.0.0.1
#port: 3333 #port: 3333
...@@ -50,5 +52,6 @@ menu: ...@@ -50,5 +52,6 @@ menu:
smd: smd:
filePath: filePath:
userName:
password:
\ No newline at end of file \ No newline at end of file
userName : Administrator
password : FjAdmin
url: http://175.41.238.212:80/
\ No newline at end of file \ No newline at end of file
支持 Markdown 格式
你添加了 0 到此讨论。请谨慎行事。
Finish editing this message first!