记录一次ssh-1v1人脸比对定制项目
目录
3.图片存入本地webapp路径下面(静态资源目录),然后以url方式可以访问
1.struts2 action接收json入参
private String getStrResponse() {
ActionContext ctx = ActionContext.getContext();
HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
StringBuilder strResponse = new StringBuilder();
try (InputStream inputStream = request.getInputStream()) {
String strMessage = null;
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
while ((strMessage = reader.readLine()) != null) {
strResponse.append(strMessage);
}
reader.close();
} catch (IOException e) {
logger.error("Failed to parse request parameters!", e);
}
return strResponse.toString();
}
2. 本地图片转base64字符串
/**
* 本地图片转base64字符串
*
* @param imgPath
*/
private static String imageToBase64(String imgPath) {
byte[] data = null;
// 读取图片字节数组
try {
InputStream in = new FileInputStream(imgPath);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
// 返回Base64编码过的字节数组字符串
String encode = encoder.encode(data);
return encode;
}
3.图片存入本地webapp路径下面(静态资源目录),然后以url方式可以访问
private FileUploadVo saveImage(String picBase64Str) {
// 1图片名称
String picType = ".jpg";
String picName = UUIDUtils.getUUID() + picType;
// 2.图片相对路径
String fileUploadPath = "fileupload/image";
String path = fileUploadPath + "/" + picName;
// 3.图片真实路径
HttpServletRequest request = getRequest();
String realFileUrl = request.getRealPath("/") + path;
//创建路径及文件名
File file = new File(realFileUrl);
File parentFile = file.getParentFile();
//构建文件夹
if (!parentFile.exists()) {
parentFile.mkdirs();
}
//将base64字符串转换为图片文件
ImageUtils.generateImage(picBase64Str, realFileUrl);
// 4.图片访问url
String url = "http://" + request.getLocalAddr() + ":80" + "/" + path;
FileUploadVo fileUploadVo = new FileUploadVo();
fileUploadVo.setRealFileUrl(realFileUrl);
fileUploadVo.setUrl(url);
return fileUploadVo;
}
4.调用接口获取人脸图片模型
/**
* @MethodName: faceImageToModel
* @Description: 获取图片模型
* @Param: [base64Str, strIp]
* @Return: java.lang.String
**/
public static String faceImageToModel(String base64Str, String strIp) {
String targetModelData = "";
try {
String url = assembleUrl(strIp, "/ISAPI/SDT/Face/pictureAnalysis");
FaceModelQo faceModelQo = new FaceModelQo();
faceModelQo.setImagesData(base64Str);
faceModelQo.setImagesType(FaceModelQo.IMAGES_TYPE_BASE64);
faceModelQo.setAlgorithmType(FaceModelQo.ALGORITHM_TYPE_FACE_MODEL);
String reqStr = JSON.toJSONString(faceModelQo);
String responseStr = HttpsClientUtil.httpsPost(url, reqStr);
logger.info("建模结果:" + responseStr);
FaceModelVo faceModelVo = JSON.parseObject(responseStr, FaceModelVo.class);
targetModelData = faceModelVo.getTargets().get(0).getTargetModelData();
} catch (Exception e) {
logger.error("建模失败", e);
}
return targetModelData;
}
5.https工具类
由于jdk7默认的TLS是1.0,1.1,而我需要调用的https接口使用TLS1.2,所有需要进行相应的设置.否则报错.
jdk7需要useProtocol("TLSv1.2"),jdk8不需要
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* https工具类
*/
public class HttpsClientUtil {
public HttpsClientUtil() {
}
public static void httpsClientInit(String IP, String user, String Password) {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
Credentials credentials = new UsernamePasswordCredentials(user, Password);
credentialsProvider.setCredentials(new AuthScope(IP, 443), credentials);
HttpsClientUtil.httpsClient = HttpClients.custom().setSSLSocketFactory(HttpsClientUtil.createSSLConnSocketFactory()).setDefaultCredentialsProvider(credentialsProvider).build();
}
public static SSLConnectionSocketFactory createSSLConnSocketFactory() {
SSLConnectionSocketFactory sslsf = null;
try {
TrustStrategy trustStrategy = new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
};
// jdk7需要useProtocol("TLSv1.2"),jdk8不需要
SSLContext sslContext = new SSLContextBuilder().useProtocol("TLSv1.2").loadTrustMaterial(null, trustStrategy).build();
X509HostnameVerifier x509HostnameVerifier = new X509HostnameVerifier() {
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
public void verify(String host, SSLSocket ssl) throws IOException {
}
public void verify(String host, X509Certificate cert) throws SSLException {
}
public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
}
};
sslsf = new SSLConnectionSocketFactory(sslContext, x509HostnameVerifier);
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
return sslsf;
}
public static CloseableHttpClient httpsClient = null;
public static String httpsGet(String url) {
String Ret = "";
try {
CloseableHttpResponse response = null;
HttpGet httpGet = new HttpGet(url);
response = httpsClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Ret = "error " + statusCode;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
Ret = "error response is null";
}
Ret = EntityUtils.toString(entity, "utf-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return Ret;
}
public static String httpsPut(String url, String inboundInfo) {
String Ret = "";
try {
CloseableHttpResponse response = null;
HttpPut httpPut = new HttpPut(url);
HttpEntity inboundInfoEntity = new StringEntity(inboundInfo, "UTF-8");
httpPut.setEntity(inboundInfoEntity);
response = httpsClient.execute(httpPut);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Ret = "error " + statusCode;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
Ret = "error response is null";
}
Ret = EntityUtils.toString(entity, "utf-8");
httpPut.releaseConnection();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return Ret;
}
public static String httpsPost(String url, String inboundInfo) {
String Ret = "";
try {
CloseableHttpResponse response = null;
HttpPost httpPost = new HttpPost(url);
HttpEntity inboundInfoEntity = new StringEntity(inboundInfo, "UTF-8");
httpPost.setEntity(inboundInfoEntity);
response = httpsClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Ret = "error " + statusCode;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
Ret = "error response is null";
}
Ret = EntityUtils.toString(entity, "utf-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return Ret;
}
public static String httpsDelete(String url) {
String Ret = "";
try {
CloseableHttpResponse response = null;
HttpDelete httpDelete = new HttpDelete(url);
response = httpsClient.execute(httpDelete);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Ret = "error " + statusCode;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
Ret = "error response is null";
}
Ret = EntityUtils.toString(entity, "utf-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return Ret;
}
public static String doPostStorageCloud(String url, String json, String faceimage, String boundary) throws Exception {
String Ret = "";
try {
CloseableHttpResponse response = null;
HttpPost method = new HttpPost(url);
method.addHeader("Accept", "text/html, application/xhtml+xml");
method.addHeader("Accept-Language", "zh-CN");
method.addHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
method.addHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
method.addHeader("Accept-Encoding", "gzip, deflate");
method.addHeader("Connection", "Keep-Alive");
method.addHeader("Cache-Control", "no-cache");
// byte szTemp
String bodyParam = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"uploadStorageCloud\";\r\n" + "Content-Type: text/json\r\n" + "Content-Length: " + Integer.toString(json.length()) + "\r\n\r\n" + json + "\r\n" + "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"imageData\";\r\n" + "Content-Type: image/jpeg\r\n" + "Content-Length: " + Integer.toString(faceimage.length()) + "\r\n\r\n" + faceimage + "\r\n--" + boundary + "--\r\n";
//HttpEntity inboundInfoEntity = new StringEntity(bodyParam, "UTF-8");
HttpEntity inboundInfoEntity = new StringEntity(bodyParam);
String strTemp = inboundInfoEntity.toString();
String strTemppp = strTemp;
method.setEntity(inboundInfoEntity);
response = httpsClient.execute(method);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Ret = "error " + statusCode;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
Ret = "error response is null";
}
Ret = EntityUtils.toString(entity, "utf-8");
method.releaseConnection();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return Ret;
}
public static String doModFacePicRecord(String url, String json, String faceimage, String boundary) throws Exception {
String Ret = "";
try {
CloseableHttpResponse response = null;
HttpPost method = new HttpPost(url);
method.addHeader("Accept", "text/html, application/xhtml+xml");
method.addHeader("Accept-Language", "zh-CN");
method.addHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
method.addHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
method.addHeader("Accept-Encoding", "gzip, deflate");
method.addHeader("Connection", "Keep-Alive");
method.addHeader("Cache-Control", "no-cache");
String bodyParam = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"FaceDataRecord\";\r\n" + "Content-Type: text/json\r\n" + "Content-Length: " + Integer.toString(json.length()) + "\r\n\r\n" + json + "\r\n" + "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"FaceImage\";\r\n" + "Content-Type: image/jpeg\r\n" + "Content-Length: " + Integer.toString(faceimage.length()) + "\r\n\r\n" + faceimage + "\r\n--" + boundary + "--\r\n";
HttpEntity inboundInfoEntity = new StringEntity(bodyParam, "UTF-8");
String strTemp = inboundInfoEntity.toString();
method.setEntity(inboundInfoEntity);
response = httpsClient.execute(method);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Ret = "error " + statusCode;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
Ret = "error response is null";
}
Ret = EntityUtils.toString(entity, "utf-8");
method.releaseConnection();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return Ret;
}
public static String doPutWithType(String url, String inbound, String charset, String Type) throws Exception {
String Ret = "";
try {
CloseableHttpResponse response = null;
HttpPut httpPut = new HttpPut(url);
httpPut.addHeader("Content-Type", Type);
HttpEntity inboundInfoEntity = new StringEntity(inbound, "UTF-8");
httpPut.setEntity(inboundInfoEntity);
response = httpsClient.execute(httpPut);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Ret = "error " + statusCode;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
Ret = "error response is null";
}
Ret = EntityUtils.toString(entity, "utf-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return Ret;
}
public static String httpsPostWithType(String url, String inboundInfo, String Type) throws Exception {
String Ret = "";
try {
CloseableHttpResponse response = null;
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", Type);
HttpEntity inboundInfoEntity = new StringEntity(inboundInfo, "UTF-8");
httpPost.setEntity(inboundInfoEntity);
response = httpsClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Ret = "error " + statusCode;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
Ret = "error response is null";
}
Ret = EntityUtils.toString(entity, "utf-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return Ret;
}
public static void main(String[] args) {
httpsClientInit("10.19.163.13", "admin", "hik12345+");
//登录校验代码待补充
String strUrl = "/ISAPI/Security/userCheck";
String strOut = HttpsClientUtil.httpsGet("https://10.19.163.13:443:" + strUrl);
System.out.println("======================" + strOut);
//
String out = HttpsClientUtil.httpsGet("https://10.19.163.13:443/ISAPI/System/deviceInfo?format=json");
System.out.println(" ########### " + out);
}
}
6.页面添加设备
/**
* @MethodName: toFaceDevicePage
* @Description: 跳到修改人脸设备页面
**/
public String toFaceDevicePage() {
faceDeviceVo = faceDeviceService.getFaceDeviceVo();
operPage = "/modules/faceDevice/config.jsp";
return DISPATCHER;
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>添加智能应用服务器</title>
</head>
<body>
<center>
<form action="/modules/faceDevice/updateFaceDevice.action" method="get">
服务器ip: <input type="text" maxlength="15" required="true" name="faceDeviceVo.strIp"
value="${faceDeviceVo.strIp}"><br>
服务器用户名: <input type="text" maxlength="50" required="true" name="faceDeviceVo.strUser"
value="${faceDeviceVo.strUser}"><br>
服务器密码: <input type="text" maxlength="200" required="true" name="faceDeviceVo.strPassword"
value="${faceDeviceVo.strPassword}"><br>
<input type="submit" value="提交">
</form>
</center>
</body>
</html>
7.接口超时时间
javaweb的httpClient默认的超时时间是30秒
但是手机端调用接口的默认超时时间是10秒
这个需要统一一下.否则手机端会把各种不同的失败情况全都判断是网络连接失败