Commit d6f0806e hjh

富士接口代码提交

1 个父辈 aa41a5d9
......@@ -39,287 +39,353 @@ import java.util.Map.Entry;
*/
@Slf4j
public class HttpHelper {
// 编码方式
private static final String CONTENT_CHARSET = "UTF-8";
// 连接超时时间
private static final int CONNECTION_TIMEOUT = 10000;
// 读数据超时时间
private static final int READ_DATA_TIMEOUT = 10000;
/**
* 兼容smdBox接口
* @param url
* @param paramMap
* @param user
* @param pwd
* @return
* @throws ApiException
*/
@Deprecated
public static String postParamWithAuth(String url, Map<String, Object> paramMap, String user, String pwd) throws ApiException {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
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;
//对其进行加密
byte[] rel = Base64.getEncoder().encode(auth.getBytes());
String res = new String(rel);
//设置认证属性
conn.setRequestProperty("Authorization", "Basic " + res);
}
// conn.setRequestProperty("Charset", "UTF-8");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 设置请求属性
String param = "";
if (paramMap != null && paramMap.size() > 0) {
Iterator<String> ite = paramMap.keySet().iterator();
while (ite.hasNext()) {
String key = ite.next();// key
Object valueObj = paramMap.get(key);
String value = "";
if (valueObj != null) {
if (valueObj instanceof Date) {
DateUtil.toDateString((Date) valueObj, "yyyyMMdd");
} else {
value = valueObj.toString();
}
}
param += key + "=" + value + "&";
}
param = param.substring(0, param.length() - 1);
}
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
throw new ApiException("Request [" + url + "] failed:" + e.getMessage());
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
throw new ApiException("Request [" + url + "] close instream failed:" + ex.getMessage());
}
}
return result;
}
public static String postJson(String url, Map<String, Object> params) throws ApiException {
// 设置请求参数
if (params == null || params.isEmpty()) {
params = null;
}
return postJsonWithAuth(url, params, null);
}
public static String postJsonWithAuth(String url, Object params, String auth) throws ApiException {
String requestBody = "";
// 设置请求参数
if (params != null) {
try {
ObjectMapper mapper = new ObjectMapper();
requestBody = mapper.writeValueAsString(params);
} catch (JsonProcessingException e) {
throw new ApiException("Request params to [" + url + "] Json failed:" + e.getMessage());
} catch (Exception e) {
throw new ApiException("Request params to [" + url + "] json exception:" + e.getMessage());
}
}
HttpPost httpPost = null;
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
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);
// 编码方式
private static final String CONTENT_CHARSET = "UTF-8";
// 连接超时时间
private static final int CONNECTION_TIMEOUT = 10000;
// 读数据超时时间
private static final int READ_DATA_TIMEOUT = 10000;
/**
* 兼容smdBox接口
*
* @param url
* @param paramMap
* @param user
* @param pwd
* @return
* @throws ApiException
*/
@Deprecated
public static String postParamWithAuth(String url, Map<String, Object> paramMap, String user, String pwd) throws ApiException {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
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;
//对其进行加密
byte[] rel = Base64.getEncoder().encode(auth.getBytes());
String res = new String(rel);
//设置认证属性
conn.setRequestProperty("Authorization", "Basic " + res);
}
// conn.setRequestProperty("Charset", "UTF-8");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 设置请求属性
String param = "";
if (paramMap != null && paramMap.size() > 0) {
Iterator<String> ite = paramMap.keySet().iterator();
while (ite.hasNext()) {
String key = ite.next();// key
Object valueObj = paramMap.get(key);
String value = "";
if (valueObj != null) {
if (valueObj instanceof Date) {
DateUtil.toDateString((Date) valueObj, "yyyyMMdd");
} else {
value = valueObj.toString();
}
}
param += key + "=" + value + "&";
}
param = param.substring(0, param.length() - 1);
}
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
throw new ApiException("Request [" + url + "] failed:" + e.getMessage());
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
throw new ApiException("Request [" + url + "] close instream failed:" + ex.getMessage());
}
}
return result;
}
public static String postJson(String url, Map<String, Object> params) throws ApiException {
// 设置请求参数
if (params == null || params.isEmpty()) {
params = null;
}
return postJsonWithAuth(url, params, null);
}
public static String postJsonWithAuth(String url, Object params, String auth) throws ApiException {
String requestBody = "";
// 设置请求参数
if (params != null) {
try {
ObjectMapper mapper = new ObjectMapper();
requestBody = mapper.writeValueAsString(params);
} catch (JsonProcessingException e) {
throw new ApiException("Request params to [" + url + "] Json failed:" + e.getMessage());
} catch (Exception e) {
throw new ApiException("Request params to [" + url + "] json exception:" + e.getMessage());
}
}
HttpPost httpPost = null;
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
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();
}
}
}
public static String postJson(String url, Map<String, Object> params, Map<String, String> headerMap) throws ApiException {
// 设置请求参数
if (params == null || params.isEmpty()) {
params = null;
}
return postJsonWithAuth(url, params, null, headerMap);
}
public static String postJsonWithAuth(String url, Object params, String auth, Map<String, String> headerMap) throws ApiException {
String requestBody = "";
// 设置请求参数
if (params != null) {
try {
ObjectMapper mapper = new ObjectMapper();
requestBody = mapper.writeValueAsString(params);
} catch (JsonProcessingException e) {
throw new ApiException("Request params to [" + url + "] Json failed:" + e.getMessage());
} catch (Exception e) {
throw new ApiException("Request params to [" + url + "] json exception:" + e.getMessage());
}
}
HttpPost httpPost = null;
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
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));
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 params to [" + url + "] 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();
}
}
}
private static List<NameValuePair> toNameValuePair(Map<String, Object> paramMap) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
if (paramMap != null && !paramMap.isEmpty()) {
//建立一个NameValuePair数组,用于存储欲传送的参数
for (Entry<String, Object> entry : paramMap.entrySet()) {
String value = "";
Object valueObj = entry.getValue();
if (valueObj != null) {
if (valueObj instanceof Date) {
value = DateUtil.toDateString((Date) valueObj, "yyyyMMdd");
} else {
value = valueObj.toString();
}
}
params.add(new BasicNameValuePair(entry.getKey(), value));
}
}
return params;
}
public static String posJsonParams(String url, Object params) throws ApiException {
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
// 设置请求参数
if (params != null) {
ObjectMapper mapper = new ObjectMapper();
try {
String requestBody = mapper.writeValueAsString(params);
httpPost.setEntity(new StringEntity(requestBody, CONTENT_CHARSET));
} catch (JsonProcessingException e) {
throw new ApiException("Request params to [" + url + "] Json failed:" + e.getMessage());
} catch (Exception e) {
throw new ApiException("Request params to [" + url + "] json exception:" + e.getMessage());
}
}
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
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 + "] failed:" + e.getMessage());
}finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static MicronResult getMicronJson(String url) throws ApiException {
if (ObjectUtil.isEmpty(url)) {
return new MicronResult();
}
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Content-Type", "application/json;charset=utf-8");
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 params to [" + url + "] 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();
}
}
}
private static List<NameValuePair> toNameValuePair(Map<String, Object> paramMap) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
if (paramMap != null && !paramMap.isEmpty()) {
//建立一个NameValuePair数组,用于存储欲传送的参数
for (Entry<String, Object> entry : paramMap.entrySet()) {
String value = "";
Object valueObj = entry.getValue();
if (valueObj != null) {
if (valueObj instanceof Date) {
value = DateUtil.toDateString((Date) valueObj, "yyyyMMdd");
} else {
value = valueObj.toString();
}
}
params.add(new BasicNameValuePair(entry.getKey(), value));
}
}
return params;
}
public static String posJsonParams(String url, Object params) throws ApiException {
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
// 设置请求参数
if (params != null) {
ObjectMapper mapper = new ObjectMapper();
try {
String requestBody = mapper.writeValueAsString(params);
httpPost.setEntity(new StringEntity(requestBody, CONTENT_CHARSET));
} catch (JsonProcessingException e) {
throw new ApiException("Request params to [" + url + "] Json failed:" + e.getMessage());
} catch (Exception e) {
throw new ApiException("Request params to [" + url + "] json exception:" + e.getMessage());
}
}
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
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 + "] failed:" + e.getMessage());
} finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static MicronResult getMicronJson(String url) throws ApiException {
if (ObjectUtil.isEmpty(url)) {
return new MicronResult();
}
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Content-Type", "application/json;charset=utf-8");
// // 设置请求参数
// if (params != null && !params.isEmpty()) {
// ObjectMapper mapper = new ObjectMapper();
......@@ -332,205 +398,205 @@ public class HttpHelper {
// throw new ApiException("Request params to [" + url + "] failed:" + e.getMessage());
// }
// }
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
httpClient = HttpClients.createDefault();
response = httpClient.execute(httpGet);
int code = response.getStatusLine().getStatusCode();
//System.out.println(response.getStatusLine().getStatusCode() + "\n");
HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET);
MicronResult result = JsonUtil.toObj(responseContent, MicronResult.class);
if (result == null) {
result = new MicronResult();
}
result.setHttpCode(code);
result.setResponseData(responseContent);
//response.close();
//httpClient.close();
return result;
} catch (Exception e) {
throw new ApiException("Request to [" + url + "] failed:" + e.getMessage());
}finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static MicronResult postMicronJson(String url, Map<String, Object> params) throws ApiException {
try {
if (ObjectUtil.isEmpty(url)) {
return new MicronResult();
}
String responseContent = postJson(url, params);
MicronResult result = JsonUtil.toObj(responseContent, MicronResult.class);
if (result == null) {
result = new MicronResult();
}
result.setResponseData(responseContent);
return result;
} catch (Exception e) {
throw new ApiException("Request to [" + url + "] failed:" + e.getMessage());
}
}
public static String getJson(String url, Object params) throws ApiException {
// 设置请求参数
if (params != null) {
try {
ObjectMapper mapper = new ObjectMapper();
String requestBody = mapper.writeValueAsString(params);
List<NameValuePair> nameValuePairs = new LinkedList<>();
nameValuePairs.add(new BasicNameValuePair("JSON", requestBody));
String paramStr = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs));
url = appendString(url, paramStr);
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
httpClient = HttpClients.createDefault();
response = httpClient.execute(httpGet);
int code = response.getStatusLine().getStatusCode();
//System.out.println(response.getStatusLine().getStatusCode() + "\n");
HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET);
MicronResult result = JsonUtil.toObj(responseContent, MicronResult.class);
if (result == null) {
result = new MicronResult();
}
result.setHttpCode(code);
result.setResponseData(responseContent);
//response.close();
//httpClient.close();
return result;
} catch (Exception e) {
throw new ApiException("Request to [" + url + "] failed:" + e.getMessage());
} finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static MicronResult postMicronJson(String url, Map<String, Object> params) throws ApiException {
try {
if (ObjectUtil.isEmpty(url)) {
return new MicronResult();
}
String responseContent = postJson(url, params);
MicronResult result = JsonUtil.toObj(responseContent, MicronResult.class);
if (result == null) {
result = new MicronResult();
}
result.setResponseData(responseContent);
return result;
} catch (Exception e) {
throw new ApiException("Request to [" + url + "] failed:" + e.getMessage());
}
}
public static String getJson(String url, Object params) throws ApiException {
// 设置请求参数
if (params != null) {
try {
ObjectMapper mapper = new ObjectMapper();
String requestBody = mapper.writeValueAsString(params);
List<NameValuePair> nameValuePairs = new LinkedList<>();
nameValuePairs.add(new BasicNameValuePair("JSON", requestBody));
String paramStr = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs));
url = appendString(url, paramStr);
// url=url+"?JSON="+requestBody;
} catch (Exception e) {
throw new ApiException("getJson append params to [" + url + "] exception:" + e.getMessage());
}
}
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
HttpGet httpGet = new HttpGet(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT).build();
httpGet.setConfig(requestConfig);
httpGet.addHeader("Content-Type", "application/json;charset=utf-8");
httpClient = HttpClients.createDefault();
response = httpClient.execute(httpGet);
int code = response.getStatusLine().getStatusCode();
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 + "] failed:" + e.getMessage());
}finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static String getJson(String url,Map<String,String> headerMap ,Object params) throws ApiException {
// 设置请求参数
if (params != null) {
try {
ObjectMapper mapper = new ObjectMapper();
String requestBody = mapper.writeValueAsString(params);
List<NameValuePair> nameValuePairs = new LinkedList<>();
nameValuePairs.add(new BasicNameValuePair("JSON", requestBody));
String paramStr = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs));
url = appendString(url, paramStr);
} catch (Exception e) {
throw new ApiException("getJson append params to [" + url + "] exception:" + e.getMessage());
}
}
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
HttpGet httpGet = new HttpGet(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT).build();
httpGet.setConfig(requestConfig);
httpGet.addHeader("Content-Type", "application/json;charset=utf-8");
httpClient = HttpClients.createDefault();
response = httpClient.execute(httpGet);
int code = response.getStatusLine().getStatusCode();
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 + "] failed:" + e.getMessage());
} finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static String getJson(String url, Map<String, String> headerMap, Object params) throws ApiException {
// 设置请求参数
if (params != null) {
try {
ObjectMapper mapper = new ObjectMapper();
String requestBody = mapper.writeValueAsString(params);
List<NameValuePair> nameValuePairs = new LinkedList<>();
nameValuePairs.add(new BasicNameValuePair("JSON", requestBody));
String paramStr = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs));
url = appendString(url, paramStr);
// url=url+"?JSON="+requestBody;
} catch (Exception e) {
throw new ApiException("getJson append params to [" + url + "] exception:" + e.getMessage());
}
}
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
HttpGet httpGet = new HttpGet(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT).build();
httpGet.setConfig(requestConfig);
if (headerMap != null && !headerMap.isEmpty()) {
for (Entry<String, String> entry : headerMap.entrySet()) {
httpGet.addHeader(entry.getKey(), entry.getValue());
}
}
httpClient = HttpClients.createDefault();
response = httpClient.execute(httpGet);
int code = response.getStatusLine().getStatusCode();
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 + "] failed:" + e.getMessage());
}finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static String postParam(String url, Map<String, Object> paramMap, Map<String,String> headerMap) throws ApiException {
// 设置请求参数
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
List<NameValuePair> params = toNameValuePair(paramMap);
URI uri = new URIBuilder(url).setParameters(params).build();
log.info("执行请求:" + uri.toString());
HttpPost httpPost = new HttpPost(uri);
for (Entry<String, String> entry : headerMap.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
} catch (Exception e) {
throw new ApiException("getJson append params to [" + url + "] exception:" + e.getMessage());
}
}
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
HttpGet httpGet = new HttpGet(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT).build();
httpGet.setConfig(requestConfig);
if (headerMap != null && !headerMap.isEmpty()) {
for (Entry<String, String> entry : headerMap.entrySet()) {
httpGet.addHeader(entry.getKey(), entry.getValue());
}
}
httpClient = HttpClients.createDefault();
response = httpClient.execute(httpGet);
int code = response.getStatusLine().getStatusCode();
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 + "] failed:" + e.getMessage());
} finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static String postParam(String url, Map<String, Object> paramMap, Map<String, String> headerMap) throws ApiException {
// 设置请求参数
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
List<NameValuePair> params = toNameValuePair(paramMap);
URI uri = new URIBuilder(url).setParameters(params).build();
log.info("执行请求:" + uri.toString());
HttpPost httpPost = new HttpPost(uri);
for (Entry<String, String> entry : headerMap.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
// httpPost.setEntity(new UrlEncodedFormEntity(params, 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 params to [" + url + "] failed:" + e.getMessage());
}finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static String appendString(String url, String paramStr) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(url);
stringBuffer.append("?");
stringBuffer.append(paramStr);
return stringBuffer.toString();
}
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 params to [" + url + "] failed:" + e.getMessage());
} finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static String appendString(String url, String paramStr) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(url);
stringBuffer.append("?");
stringBuffer.append(paramStr);
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:
host: localhost # 主机地址
port: 27017 # 端口
database: smf # 数据库
username:
password:
username: Siemens
password: Siemens
#备份数据库,如果有,则开启,注意:如果主数据库设置了用户名和密码,备份服务器必须设置用户名和密码!!
#西门子的正式和备份数据库,用户名和密码都是Siemens
#backup-mongodb:
# auto-index-creation: true # 默认为false,即不会自动创建索引
# host: localhost # 主机地址
# port: 27017 # 端口
# database: backup_smf # 数据库
# username:
# password:
backup-mongodb:
auto-index-creation: true # 默认为false,即不会自动创建索引
host: localhost # 主机地址
port: 27017 # 端口
database: backup_smf # 数据库
username: Siemens
password: Siemens
servlet:
multipart:
......
......@@ -7,6 +7,8 @@ api:
outNotifyUrl:
inNotifyUrl:
hella:
#host: 127.0.0.1
#port: 3333
......@@ -50,5 +52,6 @@ menu:
smd:
filePath:
userName:
password:
\ No newline at end of file
userName : Administrator
password : FjAdmin
url: http://175.41.238.212:80/
\ No newline at end of file
支持 Markdown 格式
你添加了 0 到此讨论。请谨慎行事。
Finish editing this message first!