精华内容
下载资源
问答
  • 海康SDK,官方资料C#、jAVA实例、说明文档海康SDK,官方资料C#、jAVA实例、说明文档。 海康SDK,官方资料C#、jAVA实例、说明文档海康SDK,官方资料C#、jAVA实例、说明文档。
  • 上一篇我们介绍了如何将康海官网的SDK示例程序在开发环境下进行加载,虽然海康官网提供的Demo文件包含了sdk绝大多数的使用方案,但如何利用海康SDK开发出一套能够利用http请求就能使网络摄像器根据相应的指令做出...

    上一篇我们介绍了如何将康海官网的SDK示例程序在开发环境下进行加载,虽然海康官网提供的Demo文件包含了sdk绝大多数的使用方案,但如何利用海康SDK开发出一套能够利用http请求就能使网络摄像器根据相应的指令做出相应的控制。今天这篇文档主要介绍一下如何利用SpringBoot框架来集成海康SDK。
    步骤一:利用idea开发工具创建SpringBoot Web应用
    具体的创建流程请看《利用Idea创建SpringBoot项目流程》
    创建完成后如下图所示:
    在这里插入图片描述
    步骤二:利用maven将SDK依赖加载到本地库中
    在maven官网中,下载maven安装程序,官网地址为http://maven.apache.org/download.cgi。
    在电脑部署maven后,需要利用相应的命令将海康SDK示例文件中的jna.jar和examples.jar两个jar包文件引入到本地的maven库中,具体的命令如下:

    mvn install:install-file -Dfile=jar地址 -DgroupId=jar组织名称 -DartifactId=jar唯一标识 -Dversion=jar版本 -Dpackaging=jar
    

    按照上面的命令将jna和examples两个jar文件引入到本地库中;同时在本SpringBoot项目中pom.xml文件中配置通过mvn命令安装到本地库的两个jar包

    步骤三:添加dll文件夹并进行相应设置
    在SpringBoot项目中添加dll文件夹,在该dll文件夹中根据《海康SDK开发1—demo文件部署运行》步骤四中介绍的dll文件和对应文件夹,全部拷贝到该文件夹中。

    步骤四:项目中引用HCNetSDK并对dll文件进行映射
    因为海康底层的SDK是通过C/C++来进行编写的,所以要想利用Java进行调用,必须将Java的接口文件与dll进行映射,为此需要将海康SDK示例文件中最最重要的HCNetSDK.java,拷贝到本SpringBoot项目中src文件夹下,同时将HCNetSDK.java中对HCNetSDK类和PlaySDK类进行dll映射的配置语句,写成dll的绝对路径。
    步骤五:编写初始化类
    将dll文件进行映射后,需要根据海康的SDK接口介绍文件,编写SDK初始化类,来对需要控制的网络设备进行配置。
    步骤六:开发controller类
    为了使SDK能够通过http请求进行控制,为此需要编写SpringBoot的controller类,来建立接收http请求的控制类。
    步骤七:项目运行
    编写好controller类后,就可以在idea或Tomcat中运行项目,然后通过postman或浏览器生成相应的http请求来实现对海康监控设备的控制。

    展开全文
  • 海康sdk

    千次阅读 2018-11-10 17:28:00
    package com.hikvision.artemis.sdk.util; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set.....
    package com.hikvision.artemis.sdk.util;
    
    import java.util.Collections;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.Set;
    import java.util.TreeMap;
    import javax.crypto.Mac;
    import javax.crypto.spec.SecretKeySpec;
    import org.apache.commons.codec.binary.Base64;
    import org.apache.commons.lang3.StringUtils;
    
    public class SignUtil
    {
      public static String sign(String secret, String method, String path, Map<String, String> headers, Map<String, String> querys, Map<String, String> bodys, List<String> signHeaderPrefixList)
      {
        try
        {
          Mac hmacSha256 = Mac.getInstance("HmacSHA256");
          byte[] keyBytes = secret.getBytes("UTF-8");
          hmacSha256.init(new SecretKeySpec(keyBytes, 0, keyBytes.length, "HmacSHA256"));
          
          return new String(Base64.encodeBase64(hmacSha256
            .doFinal(buildStringToSign(method, path, headers, querys, bodys, signHeaderPrefixList)
            .getBytes("UTF-8"))), "UTF-8");
        }
        catch (Exception e)
        {
          throw new RuntimeException(e);
        }
      }
      
      private static String buildStringToSign(String method, String path, Map<String, String> headers, Map<String, String> querys, Map<String, String> bodys, List<String> signHeaderPrefixList)
      {
        StringBuilder sb = new StringBuilder();
        
        sb.append(method.toUpperCase()).append("\n");
        if (null != headers)
        {
          if (null != headers.get("Accept"))
          {
            sb.append((String)headers.get("Accept"));
            sb.append("\n");
          }
          if (null != headers.get("Content-MD5"))
          {
            sb.append((String)headers.get("Content-MD5"));
            sb.append("\n");
          }
          if (null != headers.get("Content-Type"))
          {
            sb.append((String)headers.get("Content-Type"));
            sb.append("\n");
          }
          if (null != headers.get("Date"))
          {
            sb.append((String)headers.get("Date"));
            sb.append("\n");
          }
        }
        sb.append(buildHeaders(headers, signHeaderPrefixList));
        sb.append(buildResource(path, querys, bodys));
        return sb.toString();
      }
      
      private static String buildResource(String path, Map<String, String> querys, Map<String, String> bodys)
      {
        StringBuilder sb = new StringBuilder();
        if (!StringUtils.isBlank(path)) {
          sb.append(path);
        }
        Map<String, String> sortMap = new TreeMap();
        if (null != querys) {
          for (Map.Entry<String, String> query : querys.entrySet()) {
            if (!StringUtils.isBlank((CharSequence)query.getKey())) {
              sortMap.put(query.getKey(), query.getValue());
            }
          }
        }
        if (null != bodys) {
          for (??? = bodys.entrySet().iterator(); ???.hasNext();)
          {
            body = (Map.Entry)???.next();
            if (!StringUtils.isBlank((CharSequence)body.getKey())) {
              sortMap.put(body.getKey(), body.getValue());
            }
          }
        }
        Map.Entry<String, String> body;
        StringBuilder sbParam = new StringBuilder();
        for (Map.Entry<String, String> item : sortMap.entrySet()) {
          if (!StringUtils.isBlank((CharSequence)item.getKey()))
          {
            if (0 < sbParam.length()) {
              sbParam.append("&");
            }
            sbParam.append((String)item.getKey());
            if (!StringUtils.isBlank((CharSequence)item.getValue())) {
              sbParam.append("=").append((String)item.getValue());
            }
          }
        }
        if (0 < sbParam.length())
        {
          sb.append("?");
          sb.append(sbParam);
        }
        return sb.toString();
      }
      
      private static String buildHeaders(Map<String, String> headers, List<String> signHeaderPrefixList)
      {
        StringBuilder sb = new StringBuilder();
        if (null != signHeaderPrefixList)
        {
          signHeaderPrefixList.remove("x-ca-signature");
          signHeaderPrefixList.remove("Accept");
          signHeaderPrefixList.remove("Content-MD5");
          signHeaderPrefixList.remove("Content-Type");
          signHeaderPrefixList.remove("Date");
          Collections.sort(signHeaderPrefixList);
        }
        if (null != headers)
        {
          Map<String, String> sortMap = new TreeMap();
          sortMap.putAll(headers);
          StringBuilder signHeadersStringBuilder = new StringBuilder();
          for (Map.Entry<String, String> header : sortMap.entrySet()) {
            if (isHeaderToSign((String)header.getKey(), signHeaderPrefixList))
            {
              sb.append((String)header.getKey());
              sb.append(":");
              if (!StringUtils.isBlank((CharSequence)header.getValue())) {
                sb.append((String)header.getValue());
              }
              sb.append("\n");
              if (0 < signHeadersStringBuilder.length()) {
                signHeadersStringBuilder.append(",");
              }
              signHeadersStringBuilder.append((String)header.getKey());
            }
          }
          headers.put("x-ca-signature-headers", signHeadersStringBuilder.toString());
        }
        return sb.toString();
      }
      
      private static boolean isHeaderToSign(String headerName, List<String> signHeaderPrefixList)
      {
        if (StringUtils.isBlank(headerName)) {
          return false;
        }
        if (headerName.startsWith("x-ca-")) {
          return true;
        }
        if (null != signHeaderPrefixList) {
          for (String signHeaderPrefix : signHeaderPrefixList) {
            if (headerName.equalsIgnoreCase(signHeaderPrefix)) {
              return true;
            }
          }
        }
        return false;
      }
    }
    package com.hikvision.artemis.sdk.util;
    
    import java.io.UnsupportedEncodingException;
    import java.net.URLEncoder;
    import java.security.KeyManagementException;
    import java.security.NoSuchAlgorithmException;
    import java.security.cert.X509Certificate;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.Set;
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509TrustManager;
    import org.apache.commons.lang3.StringUtils;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    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.ClientConnectionManager;
    import org.apache.http.conn.scheme.Scheme;
    import org.apache.http.conn.scheme.SchemeRegistry;
    import org.apache.http.conn.ssl.SSLSocketFactory;
    import org.apache.http.entity.ByteArrayEntity;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    
    public class HttpUtils
    {
      public static HttpResponse doGet(String host, String path, String method, Map<String, String> headers, Map<String, String> querys)
        throws Exception
      {
        HttpClient httpClient = wrapClient(host);
        
        HttpGet request = new HttpGet(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
          request.addHeader((String)e.getKey(), (String)e.getValue());
        }
        return httpClient.execute(request);
      }
      
      public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, Map<String, String> bodys)
        throws Exception
      {
        HttpClient httpClient = wrapClient(host);
        
        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Iterator localIterator = headers.entrySet().iterator(); localIterator.hasNext();)
        {
          e = (Map.Entry)localIterator.next();
          request.addHeader((String)e.getKey(), (String)e.getValue());
        }
        Map.Entry<String, String> e;
        if (bodys != null)
        {
          Object nameValuePairList = new ArrayList();
          for (String key : bodys.keySet()) {
            ((List)nameValuePairList).add(new BasicNameValuePair(key, (String)bodys.get(key)));
          }
          UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity((List)nameValuePairList, "utf-8");
          formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
          request.setEntity(formEntity);
        }
        return httpClient.execute(request);
      }
      
      public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, String body)
        throws Exception
      {
        HttpClient httpClient = wrapClient(host);
        
        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
          request.addHeader((String)e.getKey(), (String)e.getValue());
        }
        if (StringUtils.isNotBlank(body)) {
          request.setEntity(new StringEntity(body, "utf-8"));
        }
        return httpClient.execute(request);
      }
      
      public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, byte[] body)
        throws Exception
      {
        HttpClient httpClient = wrapClient(host);
        
        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
          request.addHeader((String)e.getKey(), (String)e.getValue());
        }
        if (body != null) {
          request.setEntity(new ByteArrayEntity(body));
        }
        return httpClient.execute(request);
      }
      
      public static HttpResponse doPut(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, String body)
        throws Exception
      {
        HttpClient httpClient = wrapClient(host);
        
        HttpPut request = new HttpPut(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
          request.addHeader((String)e.getKey(), (String)e.getValue());
        }
        if (StringUtils.isNotBlank(body)) {
          request.setEntity(new StringEntity(body, "utf-8"));
        }
        return httpClient.execute(request);
      }
      
      public static HttpResponse doPut(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, byte[] body)
        throws Exception
      {
        HttpClient httpClient = wrapClient(host);
        
        HttpPut request = new HttpPut(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
          request.addHeader((String)e.getKey(), (String)e.getValue());
        }
        if (body != null) {
          request.setEntity(new ByteArrayEntity(body));
        }
        return httpClient.execute(request);
      }
      
      public static HttpResponse doDelete(String host, String path, String method, Map<String, String> headers, Map<String, String> querys)
        throws Exception
      {
        HttpClient httpClient = wrapClient(host);
        
        HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
          request.addHeader((String)e.getKey(), (String)e.getValue());
        }
        return httpClient.execute(request);
      }
      
      private static String buildUrl(String host, String path, Map<String, String> querys)
        throws UnsupportedEncodingException
      {
        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(host);
        if (!StringUtils.isBlank(path)) {
          sbUrl.append(path);
        }
        if (null != querys)
        {
          StringBuilder sbQuery = new StringBuilder();
          for (Map.Entry<String, String> query : querys.entrySet())
          {
            if (0 < sbQuery.length()) {
              sbQuery.append("&");
            }
            if ((StringUtils.isBlank((CharSequence)query.getKey())) && (!StringUtils.isBlank((CharSequence)query.getValue()))) {
              sbQuery.append((String)query.getValue());
            }
            if (!StringUtils.isBlank((CharSequence)query.getKey()))
            {
              sbQuery.append((String)query.getKey());
              if (!StringUtils.isBlank((CharSequence)query.getValue()))
              {
                sbQuery.append("=");
                sbQuery.append(URLEncoder.encode((String)query.getValue(), "utf-8"));
              }
            }
          }
          if (0 < sbQuery.length()) {
            sbUrl.append("?").append(sbQuery);
          }
        }
        return sbUrl.toString();
      }
      
      private static HttpClient wrapClient(String host)
      {
        HttpClient httpClient = new DefaultHttpClient();
        if (host.startsWith("https://")) {
          sslClient(httpClient);
        }
        return httpClient;
      }
      
      private static void sslClient(HttpClient httpClient)
      {
        try
        {
          SSLContext ctx = SSLContext.getInstance("TLS");
          X509TrustManager tm = new X509TrustManager()
          {
            public X509Certificate[] getAcceptedIssuers()
            {
              return null;
            }
            
            public void checkClientTrusted(X509Certificate[] xcs, String str) {}
            
            public void checkServerTrusted(X509Certificate[] xcs, String str) {}
          };
          ctx.init(null, new TrustManager[] { tm }, null);
          SSLSocketFactory ssf = new SSLSocketFactory(ctx);
          ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
          ClientConnectionManager ccm = httpClient.getConnectionManager();
          SchemeRegistry registry = ccm.getSchemeRegistry();
          registry.register(new Scheme("https", 443, ssf));
        }
        catch (KeyManagementException ex)
        {
          throw new RuntimeException(ex);
        }
        catch (NoSuchAlgorithmException ex)
        {
          throw new RuntimeException(ex);
        }
      }
    }

    doget

    package com.hikvision.artemis.sdk;
    
    import com.hikvision.artemis.sdk.config.ArtemisConfig;
    import com.hikvision.artemis.sdk.enums.Method;
    import com.hikvision.artemis.sdk.util.MessageDigestUtil;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import org.apache.commons.lang3.StringUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    public class ArtemisHttpUtil
    {
      private static final Logger logger = LoggerFactory.getLogger(ArtemisHttpUtil.class);
      private static final List<String> CUSTOM_HEADERS_TO_SIGN_PREFIX = new ArrayList();
      private static final String SUCC_PRE = "2";
      
      public static String doGetArtemis(Map<String, String> path, Map<String, String> querys, String accept, String contentType)
      {
        String httpSchema = (String)path.keySet().toArray()[0];
        if ((httpSchema == null) || (StringUtils.isEmpty(httpSchema))) {
          throw new RuntimeException("http��https��������httpSchema: " + httpSchema);
        }
        String responseStr = null;
        try
        {
          Map<String, String> headers = new HashMap();
          if (StringUtils.isNotBlank(accept)) {
            headers.put("Accept", accept);
          } else {
            headers.put("Accept", "*/*");
          }
          if (StringUtils.isNotBlank(contentType)) {
            headers.put("Content-Type", contentType);
          } else {
            headers.put("Content-Type", "application/text;charset=UTF-8");
          }
          CUSTOM_HEADERS_TO_SIGN_PREFIX.clear();
          
          Request request = new Request(Method.GET, httpSchema + ArtemisConfig.host, (String)path.get(httpSchema), ArtemisConfig.appKey, ArtemisConfig.appSecret, 2000);
          request.setHeaders(headers);
          request.setSignHeaderPrefixList(CUSTOM_HEADERS_TO_SIGN_PREFIX);
          
          request.setQuerys(querys);
          
          Response response = Client.execute(request);
          
          responseStr = getResponseResult(response);
        }
        catch (Exception e)
        {
          logger.error("the Artemis GET Request is failed[doGetArtemis]", e);
        }
        return responseStr;
      }
      
      public static String doPostFormArtemis(Map<String, String> path, Map<String, String> paramMap, Map<String, String> querys, String accept, String contentType)
      {
        String httpSchema = (String)path.keySet().toArray()[0];
        if ((httpSchema == null) || (StringUtils.isEmpty(httpSchema))) {
          throw new RuntimeException("http��https��������httpSchema: " + httpSchema);
        }
        String responseStr = null;
        try
        {
          Map<String, String> headers = new HashMap();
          if (StringUtils.isNotBlank(accept)) {
            headers.put("Accept", accept);
          } else {
            headers.put("Accept", "*/*");
          }
          if (StringUtils.isNotBlank(contentType)) {
            headers.put("Content-Type", contentType);
          } else {
            headers.put("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
          }
          CUSTOM_HEADERS_TO_SIGN_PREFIX.clear();
          
          Request request = new Request(Method.POST_FORM, httpSchema + ArtemisConfig.host, (String)path.get(httpSchema), ArtemisConfig.appKey, ArtemisConfig.appSecret, 2000);
          request.setHeaders(headers);
          request.setSignHeaderPrefixList(CUSTOM_HEADERS_TO_SIGN_PREFIX);
          
          request.setQuerys(querys);
          
          request.setBodys(paramMap);
          
          Response response = Client.execute(request);
          
          responseStr = getResponseResult(response);
        }
        catch (Exception e)
        {
          logger.error("the Artemis PostForm Request is failed[doPostFormArtemis]", e);
        }
        return responseStr;
      }
      
      public static String doPostStringArtemis(Map<String, String> path, String body, Map<String, String> querys, String accept, String contentType)
      {
        String httpSchema = (String)path.keySet().toArray()[0];
        if ((httpSchema == null) || (StringUtils.isEmpty(httpSchema))) {
          throw new RuntimeException("http��https��������httpSchema: " + httpSchema);
        }
        String responseStr = null;
        try
        {
          Map<String, String> headers = new HashMap();
          if (StringUtils.isNotBlank(accept)) {
            headers.put("Accept", accept);
          } else {
            headers.put("Accept", "*/*");
          }
          if (StringUtils.isNotBlank(contentType)) {
            headers.put("Content-Type", contentType);
          } else {
            headers.put("Content-Type", "application/text;charset=UTF-8");
          }
          CUSTOM_HEADERS_TO_SIGN_PREFIX.clear();
          
          Request request = new Request(Method.POST_STRING, httpSchema + ArtemisConfig.host, (String)path.get(httpSchema), ArtemisConfig.appKey, ArtemisConfig.appSecret, 2000);
          request.setHeaders(headers);
          request.setSignHeaderPrefixList(CUSTOM_HEADERS_TO_SIGN_PREFIX);
          
          request.setQuerys(querys);
          
          request.setStringBody(body);
          
          Response response = Client.execute(request);
          
          responseStr = getResponseResult(response);
        }
        catch (Exception e)
        {
          logger.error("the Artemis PostString Request is failed[doPostStringArtemis]", e);
        }
        return responseStr;
      }
      
      public static String doPostBytesArtemis(Map<String, String> path, byte[] bytesBody, Map<String, String> querys, String accept, String contentType)
      {
        String httpSchema = (String)path.keySet().toArray()[0];
        if ((httpSchema == null) || (StringUtils.isEmpty(httpSchema))) {
          throw new RuntimeException("http��https��������httpSchema: " + httpSchema);
        }
        String responseStr = null;
        try
        {
          Map<String, String> headers = new HashMap();
          if (StringUtils.isNotBlank(accept)) {
            headers.put("Accept", accept);
          } else {
            headers.put("Accept", "*/*");
          }
          if (bytesBody != null) {
            headers.put("Content-MD5", MessageDigestUtil.base64AndMD5(bytesBody));
          }
          if (StringUtils.isNotBlank(contentType)) {
            headers.put("Content-Type", contentType);
          } else {
            headers.put("Content-Type", "application/text;charset=UTF-8");
          }
          CUSTOM_HEADERS_TO_SIGN_PREFIX.clear();
          
          Request request = new Request(Method.POST_BYTES, httpSchema + ArtemisConfig.host, (String)path.get(httpSchema), ArtemisConfig.appKey, ArtemisConfig.appSecret, 2000);
          request.setHeaders(headers);
          request.setSignHeaderPrefixList(CUSTOM_HEADERS_TO_SIGN_PREFIX);
          
          request.setQuerys(querys);
          request.setBytesBody(bytesBody);
          
          Response response = Client.execute(request);
          
          responseStr = getResponseResult(response);
        }
        catch (Exception e)
        {
          logger.error("the Artemis PostBytes Request is failed[doPostBytesArtemis]", e);
        }
        return responseStr;
      }
      
      public static String doPutStringArtemis(Map<String, String> path, String body, String accept, String contentType)
      {
        String httpSchema = (String)path.keySet().toArray()[0];
        if ((httpSchema == null) || (StringUtils.isEmpty(httpSchema))) {
          throw new RuntimeException("http��https��������httpSchema: " + httpSchema);
        }
        String responseStr = null;
        try
        {
          Map<String, String> headers = new HashMap();
          if (StringUtils.isNotBlank(accept)) {
            headers.put("Accept", accept);
          } else {
            headers.put("Accept", "*/*");
          }
          if (StringUtils.isNotBlank(body)) {
            headers.put("Content-MD5", MessageDigestUtil.base64AndMD5(body));
          }
          if (StringUtils.isNotBlank(contentType)) {
            headers.put("Content-Type", contentType);
          } else {
            headers.put("Content-Type", "application/text;charset=UTF-8");
          }
          CUSTOM_HEADERS_TO_SIGN_PREFIX.clear();
          
          Request request = new Request(Method.PUT_STRING, httpSchema + ArtemisConfig.host, (String)path.get(httpSchema), ArtemisConfig.appKey, ArtemisConfig.appSecret, 2000);
          request.setHeaders(headers);
          request.setSignHeaderPrefixList(CUSTOM_HEADERS_TO_SIGN_PREFIX);
          request.setStringBody(body);
          
          Response response = Client.execute(request);
          
          responseStr = getResponseResult(response);
        }
        catch (Exception e)
        {
          logger.error("the Artemis PutString Request is failed[doPutStringArtemis]", e);
        }
        return responseStr;
      }
      
      public static String doPutBytesArtemis(Map<String, String> path, byte[] bytesBody, String accept, String contentType)
      {
        String httpSchema = (String)path.keySet().toArray()[0];
        if ((httpSchema == null) || (StringUtils.isEmpty(httpSchema))) {
          throw new RuntimeException("http��https��������httpSchema: " + httpSchema);
        }
        String responseStr = null;
        try
        {
          Map<String, String> headers = new HashMap();
          if (StringUtils.isNotBlank(accept)) {
            headers.put("Accept", accept);
          } else {
            headers.put("Accept", "*/*");
          }
          if (bytesBody != null) {
            headers.put("Content-MD5", MessageDigestUtil.base64AndMD5(bytesBody));
          }
          if (StringUtils.isNotBlank(contentType)) {
            headers.put("Content-Type", contentType);
          } else {
            headers.put("Content-Type", "application/text;charset=UTF-8");
          }
          CUSTOM_HEADERS_TO_SIGN_PREFIX.clear();
          
          Request request = new Request(Method.PUT_BYTES, httpSchema + ArtemisConfig.host, (String)path.get(httpSchema), ArtemisConfig.appKey, ArtemisConfig.appSecret, 2000);
          request.setHeaders(headers);
          request.setSignHeaderPrefixList(CUSTOM_HEADERS_TO_SIGN_PREFIX);
          request.setBytesBody(bytesBody);
          
          Response response = Client.execute(request);
          
          responseStr = getResponseResult(response);
        }
        catch (Exception e)
        {
          logger.error("the Artemis PutBytes Request is failed[doPutBytesArtemis]", e);
        }
        return responseStr;
      }
      
      public static String doDeleteArtemis(Map<String, String> path, Map<String, String> querys, String accept, String contentType)
      {
        String httpSchema = (String)path.keySet().toArray()[0];
        if ((httpSchema == null) || (StringUtils.isEmpty(httpSchema))) {
          throw new RuntimeException("http��https��������httpSchema: " + httpSchema);
        }
        String responseStr = null;
        try
        {
          Map<String, String> headers = new HashMap();
          if (StringUtils.isNotBlank(accept)) {
            headers.put("Accept", accept);
          } else {
            headers.put("Accept", "*/*");
          }
          if (StringUtils.isNotBlank(contentType)) {
            headers.put("Content-Type", contentType);
          }
          Request request = new Request(Method.DELETE, httpSchema + ArtemisConfig.host, (String)path.get(httpSchema), ArtemisConfig.appKey, ArtemisConfig.appSecret, 2000);
          request.setHeaders(headers);
          request.setSignHeaderPrefixList(CUSTOM_HEADERS_TO_SIGN_PREFIX);
          request.setQuerys(querys);
          
          Response response = Client.execute(request);
          
          responseStr = getResponseResult(response);
        }
        catch (Exception e)
        {
          logger.error("the Artemis DELETE Request is failed[doDeleteArtemis]", e);
        }
        return responseStr;
      }
      
      private static String getResponseResult(Response response)
      {
        String responseStr = null;
        
        int statusCode = response.getStatusCode();
        if (String.valueOf(statusCode).startsWith("2"))
        {
          responseStr = response.getBody();
          logger.info("the Artemis Request is Success,statusCode:" + statusCode + " SuccessMsg:" + response.getBody());
        }
        else
        {
          String msg = response.getErrorMessage();
          responseStr = response.getBody();
          logger.error("the Artemis Request is Failed,statusCode:" + statusCode + " errorMsg:" + msg);
        }
        return responseStr;
      }
    }
    package com.hikvision.ga;
    
    import java.util.HashMap;
    import java.util.Map;
    
    import com.hikvision.artemis.sdk.ArtemisHttpUtil;
    import com.hikvision.artemis.sdk.config.ArtemisConfig;
    
    /**
     * ��Class��������, ����������������������, ��������������������������������������.
     * ������������������:
     *     [1] ����������������������
     *     https://open8200.hikvision.com/artemis-portal/document?version=4&docId=306&apiBlock=1
     *     [2] ����appKey������������
     *  https://open8200.hikvision.com/artemis-portal/document?version=4&docId=284&apiBlock=2
     * @author zhangtuo
     *
     */
    public class ArtemisTest {
    
        /**
         * ������������appKey��appSecret����static������������������.
         * [1 host]
         *         ����������������open8200����,������������������,������������������,host��������.������open8200.hikvision.com
         *         ����������������������������,host������������������ip,����1.0 ��������������9999.����2.0 ��������������443.����:10.33.25.22:9999 ����10.33.25.22:443
         * [2 appKey��appSecret]
         *         ��������������appKey��appSecret����.
         *         
         * ps. ����������open8200��������������������,��������������,��������������,������������.
         * 
         */
        static {
            ArtemisConfig.host ="open8200.hikvision.com"; //artemis����������ip����
            ArtemisConfig.appKey ="22425132";     //����appkey
            ArtemisConfig.appSecret ="mcsioUGkT5GRMZTvjwAC";//����appSecret
        }
        /**
         * ����������������������
         * TODO ������������������/artemis
         */
        private static final String ARTEMIS_PATH = "/artemis";
        
        /**
         * [1] ������������������������������
         * @return
         */
        public static String callApiGetCameraInfos() {
            /**
             *     https://open8200.hikvision.com/artemis-portal/document?version=4&docId=306&apiBlock=1
             *  ����API��������������,��������GET������Rest����, ������������������queryString, ����������������������:
             *      http://ip:port/path?a=1&b=2
             *  ArtemisHttpUtil������������doGetArtemis��������, ����������������������������������.
             *  ����������https, ��������������path����hashmap����,��put����key-value, querys������������.
             *  start��������, size��������.
             */
            String getCamsApi = ARTEMIS_PATH + "/api/common/v1/remoteCameraInfoRestService/findCameraInfoPage";
            Map<String,String> querys = new HashMap<String,String>();//get��������������
            querys.put("start", "0");
            querys.put("size", "20");
            Map<String, String> path = new HashMap<String, String>(2){
                {
                     put("https://", getCamsApi);
                }
            };
            String result = ArtemisHttpUtil.doGetArtemis(path, querys,null,null);
            return result;
        }
        
        /**
         * [2] ����appKey������������
         * @return
         */
        public static String callApiGetSecurity() {
            /**
             *     https://open8200.hikvision.com/artemis-portal/document?version=4&docId=284&apiBlock=2
             *  ����API��������������,��������GET������Rest����,
             *  ����������������Parameter Path,����queryString����������.
             *  ��������: /api/artemis/v1/agreementService/securityParam/appKey/{appKey}
             *  {appKey}��Parameter Path
             *  ����, doGetArtemis����������������null
             *
             *  TODO ��������������appKey����������static��������������appKey
             */
            String getSecurityApi = ARTEMIS_PATH + "/api/artemis/v1/agreementService/securityParam/appKey/22425132";
            Map<String, String> path = new HashMap<String, String>(2){
                {
                     put("https://", getSecurityApi);
                }
            };
            String result = ArtemisHttpUtil.doGetArtemis(path, null,null,null);
            return result;
        }
        
        public static void main(String[] args) {
            /**
             * ������������������
             */
            String camsResult = callApiGetCameraInfos();
            
            /**
             * ����appKey������������
             */
            String securityResult = callApiGetSecurity();
            System.out.println(camsResult);
            System.out.println(securityResult);
        }
    }

     

    转载于:https://www.cnblogs.com/longyi/p/9940014.html

    展开全文
  • 海康sdk需要的dll文件
  • Delphi海康SDK开发

    2018-04-17 21:03:01
    海康SDK二次开发系统简单应用,可以实现海康硬盘录像机视频服务器登录预览
  • qt for 海康sdk

    2017-05-08 14:13:48
    qt for 海康sdk
  • 海康SDK源码

    2014-11-12 17:41:24
    海康SDK的源码,内有说明文档和源代码。说明的非常详细
  • 海康SDK_串口解析工具合集海康SDK_串口解析工具合集海康SDK_串口解析工具合集
  • MFC调用海康SDK

    2017-11-30 16:29:10
    MFC调用海康SDK,亲自测试过,可以正常使用,也比较实用的,如有需要可以下载啊。
  • 海康SDK开发包

    2017-11-30 16:15:23
    海康SDK开发文档,包括CVR、IPC、ITS、LCD屏、报警主机、解码器、热成像、抓拍机......
  • Java+海康SDK DEMO

    2020-12-05 14:11:07
    Java SpringBoot框架+海康SDK Linux版本代码,集成了所需的告警DEMO(存储在influxDB)。有获取该NVR下所有设备的接口,以及获取该NVR下某个时间段的视频文件下载,并转成MP4文件。
  • python 调用海康SDK 控制摄像头云台代码
  • Delphi 海康SDK视频预览测试,版本不限
  • 海康SDK接口说明

    2016-01-19 16:43:39
    海康SDK接口说明,方便用户对响应摄像头项目进行开发。
  • 使用大华、海康SDK开发的一个小程序,可以多界面播放
  • 使用go语言,调用海康SDK,完成一些基本的操作
  • 海康SDK delphi demo

    热门讨论 2013-05-23 11:02:57
    海康sdk二次开发delphi例程,包括回调函数
  • 海康SDK在WPF运用.zip

    2020-02-12 17:16:14
    海康SDK与WPF的结合,易上手。运行时修改HCNetSDK.dll目录,基于.NET WPF开发。
  • java调用海康sdk案例

    2019-03-05 17:21:03
    基于海康SDK和java版ClientDemo,移植到idea。完全可用,出现无法加载jar包情况请选择lib下的jar add as library。最后选中ClientDemo.java,右击选择运行,就完成了。
  • 海康sdk二次开发代码

    2018-01-02 14:04:55
    海康sdk二次开发代码demo,包括浏览视频和控制摄像头等操作
  • 海康sdk开发事例

    2013-04-18 23:15:30
    海康sdk开发事例,提供对视频的接口 ,可开发出视频调用控件,使视频清晰可见
  • 海康sdk报错

    2021-09-26 09:52:52
    1.海康sdk报错Linux版本 java.lang.Error: Structure.getFieldOrder() on class com.cspid.hikvisionSDK.HCNetSDKNETDVRUSERLOGININFOdoesnotprovideenoughnames[0]([])tomatchdeclaredfields[8]([bUseAsynLogin,...

    技术交流QQ群 933925017

    1.海康sdk报错Linux版本

    java.lang.Error: Structure.getFieldOrder() on class com.cspid.hikvisionSDK.HCNetSDK N E T D V R U S E R L O G I N I N F O d o e s n o t p r o v i d e e n o u g h n a m e s [ 0 ] ( [ ] ) t o m a t c h d e c l a r e d f i e l d s [ 8 ] ( [ b U s e A s y n L o g i n , b y R e s 2 , b y U s e T r a n s p o r t , c b L o g i n R e s u l t , s D e v i c e A d d r e s s , s P a s s w o r d , s U s e r N a m e , w P o r t ] ) ] w i t h r o o t c a u s e j a v a . l a n g . E r r o r : S t r u c t u r e . g e t F i e l d O r d e r ( ) o n c l a s s c o m . c s p i d . h i k v i s i o n S D K . H C N e t S D K NET_DVR_USER_LOGIN_INFO does not provide enough names [0] ([]) to match declared fields [8] ([bUseAsynLogin, byRes2, byUseTransport, cbLoginResult, sDeviceAddress, sPassword, sUserName, wPort])] with root cause java.lang.Error: Structure.getFieldOrder() on class com.cspid.hikvisionSDK.HCNetSDK NETDVRUSERLOGININFOdoesnotprovideenoughnames[0]([])tomatchdeclaredfields[8]([bUseAsynLogin,byRes2,byUseTransport,cbLoginResult,sDeviceAddress,sPassword,sUserName,wPort])]withrootcausejava.lang.Error:Structure.getFieldOrder()onclasscom.cspid.hikvisionSDK.HCNetSDKNET_DVR_USER_LOGIN_INFO does not provide enough names [0] ([]) to match declared fields [8] ([bUseAsynLogin, byRes2, byUseTransport, cbLoginResult, sDeviceAddress, sPassword, sUserName, wPort])

    • 海康官方解释

    Java开发,报错:“java.lang.Error: Structure.getFieldOrder() on class …”或者 “The type xxx must inmplement the inherited abstract method Structure.getFiledOrder()”是什么原因?
    Java开发使用jna方式调用动态库,我们Windows和Linux版本设备网络SDK对jna版本没有限制要求,但是Java Demo中使用的jna.jar版本比较老(3.0.9版本),结构体定义没有getFiledOrder,如果开发时更新了jna(比如更新到4.5.1版本),必须增加getFieldOrder,比如:
    public static class NET_VCA_POINT extends Structure{
    public float fX;
    public float fY;
    @Override
    protected List getFieldOrder() {
    // TODO Auto-generated method stub
    return Arrays.asList(“fX”, “fY”); //这里参数顺序和SDK开发包的C++定义必须完全一致
    }
    }

    • 解决办法由于我的 jna版本高所以最佳解决办法是退回到3.0.9版本
    <!-- https://mvnrepository.com/artifact/net.java.dev.jna/jna -->
            <dependency>
                <groupId>net.java.dev.jna</groupId>
                <artifactId>jna</artifactId>
                <version>3.0.9</version>
            </dependency>
    
    展开全文
  • 用C#封装过的海康NET SDK,版本号2014
  • 易语言基于海康SDK的人脸识别应用,自己的算法,海康的原生SDK获取摄像头画面
  • 通过海康sdk捕获码流数据实现抓图功能问题描述实现方式将回调函数中的码流数据写入到管道流中读取管道流获取AVFrame帧,转为图片保存到本地 个人博客:banmajio’s blog 海康sdk二次开发系列文章 海康sdk捕获码流...

    个人博客:banmajio’s blog

    海康sdk二次开发系列文章
    海康sdk捕获码流数据通过JavaCV推成rtmp流的实现思路(PS流转封装RTMP)
    海康sdk进行历史回放时,码流数据回调过快问题的解决方法
    海康sdk项目(java)部署Linux环境相关问题总结
    海康sdk部署Linux环境下无法播放子码流的问题
    海康sdk项目部署Linux系统时出现java.lang.UnstisfiedLinkError:jnidispatch(xxx)not found in resource path错误
    通过海康sdk实现指定时间段内的录像文件下载
    海康sdk查询指定时间段内NVR的录像文件列表

    问题描述

    在对监控直播或回放进行抓图操作时,大概有三种方式。

    1. 直接使用播放器抓图,例如video.js、easyplayer.js等播放器大多提供了抓图按钮,可以直接截取播放器画面到客户端。但是缺点就是如果服务需要定时截图就无法满足了。
    2. 使用海康sdk二次开发,调用海康自己的接口如NET_DVR_PlayBackCaptureFile等接口实现抓图功能。但是这些接口无一例外,需要搭配海康的播放库才能实现,也就是需要在调用预览接口或者回放接口是传入窗口句柄,否则调用该接口无效,或返回错误码23(调用次序出错)
    3. 依旧是海康sdk二次开发,可以在预览和回放接口中传入回调函数,捕获ps封装的h264数据,通过opencv时间抓图操作

    实现方式

    本篇文章以直播的抓图为例作为教程,回放的抓图与之同理。
    首先需要明白海康sdk接口调用的流程:
    在这里插入图片描述
    如图所示,根据流程参考海康sdk文档调用接口,我们的抓图操作是要在启动预览之后,注册了回调函数,并且回调函数中有码流数据回调时进行的。

    将回调函数中的码流数据写入到管道流中

    首先确保直播预览接口调用无误,并且回调函数可以正常执行,当调用了抓图接口,回调函数中得到了抓图开始的标志 开始将回调的码流数据copy一份到管道流中。管道流的使用请参考海康sdk捕获码流数据通过JavaCV推成rtmp流的实现思路(PS流转封装RTMP)

    package com.banmajio.callback;
    
    import java.io.IOException;
    import java.io.PipedInputStream;
    import java.io.PipedOutputStream;
    
    import com.junction.sdk.HCNetSDK.FRealDataCallBack_V30;
    import com.sun.jna.NativeLong;
    import com.sun.jna.Pointer;
    import com.sun.jna.ptr.ByteByReference;
    
    /**
     * @Title RealDataCallBack.java
     * @description 实时预览回调函数
     * @time 2020年3月17日 下午2:45:08
     * @author banmajio
     **/
    public class RealDataCallBack implements FRealDataCallBack_V30 {
    
    	private PipedOutputStream outputStream;// 管道输出流
    	private PipedOutputStream picOutputStream;// 抓图管道流
    
    	public static boolean playbackcapture = false;// 开始抓图标志 true:开始抓图 false:结束抓图
    
    	public RealDataCallBack(PipedOutputStream outputStream) {
    		this.outputStream = outputStream;
    	}
    
    	public void setPicOutputStream(PipedOutputStream picOutputStream) {
    		this.picOutputStream = picOutputStream;
    	}
    
    	@Override
    	public void invoke(NativeLong lRealHandle, int dwDataType, ByteByReference pBuffer, int dwBufSize, Pointer pUser) {
    		try {
    			if (playbackcapture) {
    				// 将数据同时写入抓图管道流中
    				picOutputStream.write(pBuffer.getPointer().getByteArray(0, dwBufSize));
    			}
    			outputStream.write(pBuffer.getPointer().getByteArray(0, dwBufSize));
    		} catch (IOException e) {
    //			logger.error(e.getMessage());
    		}
    	}
    }
    
    

    读取管道流获取AVFrame帧,转为图片保存到本地

    从管道流中取出数据,喂到javacv的帧抓取器FFmpegFrameGrabber中,获取码流数据的AVFrame帧,通过opencv的函数,将帧转为图片输出。代码如下:

    package com.banmajio.play;
    
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import java.io.PipedInputStream;
    import java.io.PipedOutputStream;
    import java.util.ArrayList;
    import java.util.Date;
    
    import javax.imageio.ImageIO;
    
    import org.bytedeco.ffmpeg.global.avcodec;
    import org.bytedeco.ffmpeg.global.avutil;
    import org.bytedeco.javacv.FFmpegFrameGrabber;
    import org.bytedeco.javacv.Frame;
    import org.bytedeco.javacv.FrameGrabber.Exception;
    import org.bytedeco.javacv.Java2DFrameConverter;
    import org.bytedeco.javacv.OpenCVFrameConverter;
    import org.bytedeco.opencv.global.opencv_core;
    import org.bytedeco.opencv.opencv_core.IplImage;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    /**
     * @ClassName: PlayBackCapture
     * @Description:抓图
     * @author: banmajio
     * @date: 2020-11-13
     */
    public class PlayBackCapture {
    
    	private final static Logger logger = LoggerFactory.getLogger(PlayBackCapture.class);
    
    	private PipedInputStream picInputStream;// 抓图输入流
    	private PipedOutputStream picOutputStream;// 抓图输出流
    	private FFmpegFrameGrabber grabber;// 抓流器
    	private ArrayList<String> picturePaths = new ArrayList<>();
    
    	public PlayBackCapture(PipedInputStream picInputStream, PipedOutputStream picOutputStream) {
    		this.picInputStream = picInputStream;
    		this.picOutputStream = picOutputStream;
    	}
    
    	public void setPicturePath(String picturepath) {
    		picturePaths.add(picturepath);
    	}
    
    	public void playBackCapture(String token) throws IOException, InterruptedException {
    		try {
    			picInputStream.connect(picOutputStream);
    			grabber = new FFmpegFrameGrabber(picInputStream, 0);
    			//检测管道流中是否存在数据,如果2s后依然没有写入1024的数据,则认为管道流中无数据,避免grabber.start();发生阻塞
    			long stime = new Date().getTime();
    			while (true) {
    				Thread.sleep(100);
    				if (new Date().getTime() - stime > 2000) {
    					return;
    				}
    				if (picInputStream.available() == 1024) {
    					break;
    				}
    			}
    			grabber.start();
    			String rotate = grabber.getVideoMetadata("rotate");// 视频的旋转角度
    			Frame frame = null;
    			int frameIndex = 0;
    			int pictureIndex = 0;
    			while (frameIndex < 10) {
    			    // 获取image帧
    				frame = grabber.grabImage();
    				if (null != frame && null != frame.image) {
    					IplImage src = null;
    					if (null != rotate && rotate.length() > 1) {
    						OpenCVFrameConverter.ToIplImage converter = new OpenCVFrameConverter.ToIplImage();
    						src = converter.convert(frame);
    						frame = converter.convert(rotate(src, Integer.valueOf(rotate)));
    					}
    					doExecuteFrame(frame, picturePaths.get(pictureIndex), frameIndex);
    					logger.info("hcsdk " + " 抓图完成 保存路径为:" + picturePaths.get(pictureIndex));
    					pictureIndex++;
    					if (pictureIndex < picturePaths.size()) {
    						continue;
    					} else {
    						break;
    					}
    				}
    				frameIndex++;
    			}
    		} catch (Exception e) {
    			logger.info("hcsdk " + " 抓图失败");
    			grabber.stop();
    			grabber.close();
    			picInputStream.close();
    			picOutputStream.close();
    			e.printStackTrace();
    		}
    		grabber.stop();
    		grabber.close();
    		picInputStream.close();
    		picOutputStream.close();
    	}
    
    	private void doExecuteFrame(Frame frame, String picturepath, int frameIndex) throws IOException {
    		if (null == frame || null == frame.image) {
    			return;
    		}
    		Java2DFrameConverter converter = new Java2DFrameConverter();
    		BufferedImage bi = converter.getBufferedImage(frame);
    
    		File output = new File(picturepath);
    		try {
    			ImageIO.write(bi, "jpg", output);
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    
    	private IplImage rotate(IplImage src, Integer angle) {
    		IplImage img = IplImage.create(src.height(), src.width(), src.depth(), src.nChannels());
    		opencv_core.cvTranspose(src, img);
    		opencv_core.cvFlip(img, img, angle);
    		return img;
    	}
    }
    
    
    展开全文
  • QT海康视频播放器源码,含海康SDK

    热门讨论 2013-12-05 15:30:50
    QT做的海康视频播放器源码,包括海康sdk,qt 4.8.4 vs2012开发,包含工程文件,可运行
  • 海康SDK示例(VS.rar)

    2020-04-15 14:48:58
    知识记载:学习海康SDK的二次开发(C++)中所用的示例,就不必大家再去查找了 可以用VS2008/2010/2012/2015打开
  • LINUX版用QT C++调用海康SDK取流和控制云台
  • 海康SDK开发Demo_Java

    热门讨论 2014-03-12 12:49:36
    海康SDK开发Demo Java版本 使用设备网络SDK CH-HCNetSDK(Windows32)V4.2.1.8_2
  • 海康SDK开发运行库

    2014-03-12 12:57:37
    海康SDK开发的程序运行时需要拷贝的库集合,没有这些运行库,程序运行起来看不到画面

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 3,683
精华内容 1,473
关键字:

海康sdk