GAT1400注册和保活及上下级关系

这段代码展示了如何在Java中处理HTTP Digest认证,用于设备注册和注销。主要涉及MD5加密,通过多次HTTP请求完成认证过程,包括获取nonce、qop等信息,然后构造Authorization头并进行二次请求。代码中包含了一个注册函数和一个注销函数,每个函数都包含了从第一次请求获取验证信息到第二次请求完成操作的完整流程。
摘要由CSDN通过智能技术生成

1400协议,要搞清楚你作为上级还是下级,上级域编码和下级域编码的关系,你去注册别人,还是别人来注册你,避免遇到神坑

你作为下级----(注册)—>上级
在这里插入图片描述

不废话,直接上代码

public static void main(String[] args) {
		try{
//			System.out.println(TestImg.isExceptionQueue);
//			TestImg.isExceptionQueue = true;
//			System.out.println(TestImg.isExceptionQueue);
//			for(int i=0;i<100;i++){
//				String Authorization = test();
//				Thread.sleep(80000);
//			}
			
//			System.out.println(Authorization);
//			runble();
			test();
//			testun();
//			test();
//			String aa ="MTUzODMwMjgyNTAwMDo4YzgzYjAxZTlkY2E1YzcxYTc3NjM1YzAzNTM4NmFhMg==";
//			String HA1 = MD5.baseMd5("admin:com.harzone.viid:admin");
//			String HD = aa+":"+"00000001"+":"+"248a286a6dda379e"+":"+"auth";
//			String HA2= MD5.baseMd5("POST"+":"+"/VIID/System/Register");
			String response =  MD5.baseMd5(HA1+":"+HD+":"+HA2);
			MD5(MD5(A1):<nonce>:<nc>:<cnonce>:<qop>:MD5(A2))
			String response = MD5.baseMd5(HA1+":"+aa+":"+"00000001"+":"+"248a286a6dda379e"+":"+"auth"+":"+HA2);
//			String response = MD5.baseMd5(MD5.baseMd5("admin:com.harzone.viid:admin")+":"+"MTUzODMwMjgyNTAwMDo4YzgzYjAxZTlkY2E1YzcxYTc3NjM1YzAzNTM4NmFhMg=="+":"+"00000001"+":"+"248a286a6dda379e"+":"+"auth"+":"+MD5.baseMd5("POST"+":"+"/VIID/System/Register"));
//
//			System.out.println(response);
			//			Thread.sleep(60000);
//			String Authorization="Digest username=\"admin\", realm=\"com.harzone.viid\", qop=\"auth\", nonce=\"MTUzMDg1NzY4NDAyOTo1ODgyNzBhZWE3ZDVkZTFkNjZiZjI2MjE1YTYzMDM2YQ==\", uri=\"/VIID/System/Register\", cnonce=\"\", nc=, response=\"fc178914560068567060c6ba5d3c3b2f\"";
//			System.out.println(Authorization);
//			String tollagte = "{\"TollgateListObject\":{\"TollgateObject\": [{\"TollgateID\": \"21234567891234567893\",\"Name\": \"卡口三号\",\"Longitude\": \"112.23\",\"Latitude\": \"22.56\",\"PlaceCode\": \"100003\",\"Place\": \"深圳车公庙香蜜湖03\",\"Status\": \"0\",\"TollgateCat\": \"03\",\"TollgateUsage\": \"80\",\"LaneNum\": \"1\",\"OrgCode\": \"102001\",\"ActiveTime\": \"2018-02-01 16:32:37\"},{\"TollgateID\": \"21234567891234567899\",\"Name\": \"卡口四号1\",\"Longitude\": \"112.23598745\",\"Latitude\": \"22.568748655\",\"PlaceCode\": \"100004\",\"Place\": \"深圳车公庙香蜜湖09\",\"Status\": \"0\",\"TollgateCat\": \"04\",\"TollgateUsage\": \"80\",\"LaneNum\": \"2\",\"OrgCode\": \"102001\",\"ActiveTime\": \"2018-02-01 16:42:37\"}]}}";
//			String response = restConnect("http://10.10.10.45:8885/VIID/Tollgates", "POST", tollagte, "50000000041205952801");
//			String subscribeStr = "{\"SubscribeListObject\":{\"SubscribeObject\":[\"{\"ApplicantName\": \"string\",\"ApplicantOrg\": \"string\",\"BeginTime\": \"2018-01-30 02:17:43\",
//			String response = restConnect("http://10.10.10.45:8885/VIID/System/Keepalive", "POST", "{\"KeepaliveObject\":{\"DeviceID\":\"50000000041205952801\"}}","50000000041205952801");
//			System.out.println(response);
//			Thread.sleep(85000);
//			response = restConnect("http://10.10.10.45:8885/VIID/System/Keepalive", "POST", "{\"KeepaliveObject\":{\"DeviceID\":\"50000000041205952801\"}}","50000000041205952801");
//			System.out.println(response);
			
//			for(int i=0;i<1;i++){
//				String response = restConnect("http://10.10.10.45:8885/VIID/Faces?PageRecordNum<=2", "GET", "","");
//				System.out.println(i);
//			}
//			 Viidserver currentServer = new Viidserver();
//			 if(currentServer.getViidserverid().equals("11")){
//				 
//			 }
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public static void runble(){
		System.out.println("callable==========");
		 Thread thread = new Thread(new Runnable() {
		        @Override
		        public void run() {
		            //无返回值的业务代码
		        	System.out.println("55511111");
		        }
		    });
	   thread.start();
	}

public static String test(){
		try {
			//进入注册,计数器次数+1
			List<String> countList = new ArrayList<String>();
			countList.add("count");
			String ip = "http://10.10.10.45:8888";
			String sendJson = "{\"RegisterObject\":{\"DeviceID\":\"41000000005030312222\"}}";
			boolean successs1 = false;//判断第一次响应是否成功
			Map<String,String> map_FirstReturn = null;
			try {
				//statusCode realm qop nonce
				map_FirstReturn = restConnectForFirst(ip+"/VIID/System/Register", "POST", sendJson);
				String statusCode = map_FirstReturn.get("statusCode");
//				log.error("第一次请求StatusCode:"+statusCode);
				if(statusCode!=null && "401".equals(statusCode)){
					successs1 = true; 
				}
			} catch (Exception e) {
				e.printStackTrace();
//				log.error("第一次请求注册失败",e);
				return "01";
			}
			
			boolean successs2 = false;//判断第二次响应是否成功
			if(successs1){//进行第二次请求
				//第一次注册成功 获取响应头中的验证信息
//				log.error("第一次请求注册成功");
				String Authorization = getResponseCkInfo(map_FirstReturn,countList);
				System.out.println("Authorization="+Authorization);
//				log.error("Authorization:"+Authorization);
//				String responseStr2 = RestClient.postByRest("/VIID/System/Register", sendJson, Authorization);
				String responseStr2 = restConnectForSecond(ip+"/VIID/System/Register", "POST", sendJson, Authorization);
//				log.error("second R:"+responseStr2);
				//向发起方发送成功响应200 OK
				if("201".equals(responseStr2)){
					successs2 = true; 
				}
				System.out.println("Authorization="+Authorization);
				System.out.println("response=="+responseStr2);
				return Authorization;
			}else{
				//第一次请求失败,返回失败信息
				return "01";
			}
			

		} catch (Exception e) {
//			log.error("注册信息失败",e);
			return "01";
		}
	
	}


public static String testun(){
		try {
			//进入注册,计数器次数+1
			List<String> countList = new ArrayList<String>();
			countList.add("count");
			String ip = "http://10.10.10.45:8088";
			String sendJson = "{\"UnRegisterObject\":{\"DeviceID\":\"12345678905030000001\"}}";
			boolean successs1 = false;//判断第一次响应是否成功
			Map<String,String> map_FirstReturn = null;
			try {
				//statusCode realm qop nonce
				map_FirstReturn = restConnectForFirst(ip+"/VIID/System/UnRegister", "POST", sendJson);
				String statusCode = map_FirstReturn.get("statusCode");
//				log.error("第一次请求StatusCode:"+statusCode);
				if(statusCode!=null && "401".equals(statusCode)){
					successs1 = true; 
				}
			} catch (Exception e) {
				e.printStackTrace();
//				log.error("第一次请求注册失败",e);
				return "01";
			}
			
			boolean successs2 = false;//判断第二次响应是否成功
			if(successs1){//进行第二次请求
				//第一次注册成功 获取响应头中的验证信息
//				log.error("第一次请求注册成功");
				String Authorization = getResponseCkInfo(map_FirstReturn,countList);
				System.out.println("Authorization="+Authorization);
//				log.error("Authorization:"+Authorization);
//				String responseStr2 = RestClient.postByRest("/VIID/System/Register", sendJson, Authorization);
				String responseStr2 = restConnectForSecond(ip+"/VIID/System/UnRegister", "POST", sendJson, Authorization);
//				log.error("second R:"+responseStr2);
				//向发起方发送成功响应200 OK
				if("201".equals(responseStr2)){
					successs2 = true; 
				}
//				System.out.println("Authorization="+Authorization);
//				System.out.println("response=="+responseStr2);
				return Authorization;
			}else{
				//第一次请求失败,返回失败信息
				return "01";
			}
			

		} catch (Exception e) {
//			log.error("注册信息失败",e);
			return "01";
		}
	
	}
private static String getResponseCkInfo(Map<String, String> map_FirstReturn, List<String> countList) {
		//HA1:HD:HA2
		String username =  "admin";
		String pwd = "huawei@123";
		String realm = map_FirstReturn.get("realm");
		String nonce = map_FirstReturn.get("nonce");
		String qop = map_FirstReturn.get("qop");
		String noncecount = getHex(countList.size());
		String cnonce= "248a286a6dda379e";
		String method = "POST";
		String uri = "/VIID/System/UnRegister";
		
//		String HA1 = MD5.baseMd5(username+":"+realm+":"+pwd);
//		String HD = nonce+":::"+qop;
//		String HA2= MD5.baseMd5(method+":"+uri);
		
		String HA1 = MD5.baseMd5(username+":"+realm+":"+pwd);
		String HD = nonce+":"+noncecount+":"+cnonce+":"+qop;
		String HA2= MD5.baseMd5(method+":"+uri);
//		String response =  MD5.baseMd5(HA1+":"+HD+":"+HA2);
//		MD5(MD5(A1):<nonce>:<nc>:<cnonce>:<qop>:MD5(A2))
		String response = MD5.baseMd5(HA1+":"+nonce+":"+noncecount+":"+cnonce+":"+qop+":"+HA2);
		String Authorization = "Digest ";
		Authorization+="username=\""+username+"\", ";
		Authorization+="realm=\""+realm+"\", ";
		Authorization+="qop=\""+qop+"\", ";
		Authorization+="nonce=\""+nonce+"\", ";
		Authorization+="uri=\""+uri+"\", ";
		Authorization+="cnonce=\""+cnonce+"\", ";
//		Authorization+="cnonce=\"\", ";
		Authorization+="nc=\""+noncecount+"\", ";
//		Authorization+="nc=, ";
		Authorization+="response=\""+response+"\"";
		
//		Authorization: Digest username="xx",realm="xx",qop="auth",nonce="xx",uri="path",cnonce="xx",nc=00000001,response="xx",opaque="xx"
//		String Authorization = "{\"username\":\""+username+"\",\"realm\":\""+realm+"\",\"qop\":\""+qop+"\""
//				+ ",\"uri\":\""+uri+"\",\"cnonce\":\""+cnonce+"\",\"nc\":"+noncecount+",\"response\":\""+response+"\"}";;
//        Authorization = "Digest username=\"admin\", realm=\"com.stevex.demo\", nonce=\"MTUzMDI0NTMzNTA1NDplOTNjYmMyNzRhNzU1MzNlODFlMWRjZWZmYjEwN2MwNg==\", uri=\"/demo/list\", qop=auth, nc=, cnonce=\"\", response=\"c4d517a96b923ba6b134caaf11c305cb\", opaque=\"\"";
		return Authorization;
	}

	/*
	 * 将请求次数转为八位16进制
	 */
	private static String getHex(int size) {
		String hex = Integer.toHexString(size);
		if(hex.length()<8){
			int l = 8-hex.length();
			String zero = "";
			for (int i = 0; i < l; i++) {
				zero+="0";
			}
			hex = zero+hex;
		}
		return hex;
	}
	
	public static Map<String,String> restConnectForFirst(String url,String method,String param) throws IOException {
		Map<String,String> returnMap = new HashMap<String, String>();
			URL restUrl=new URL(url);
			HttpURLConnection conn = (HttpURLConnection) restUrl.openConnection(); 
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestMethod(method);
			conn.setUseCaches(false);
			conn.setRequestProperty("Accept-Charset", "UTF-8");	
//			conn.setRequestProperty("contentType", "UTF-8");	
				//设置访问提交模式,表单提交  
			conn.setRequestProperty("Content-Type","application/VIID+JSON");
			conn.setConnectTimeout(10000);//连接超时 单位毫秒  
			conn.setReadTimeout(5000);//读取超时 单位毫秒  
			//传递参数
			if (param != null) {
				byte[] bypes = param.toString().getBytes("utf-8");  
				conn.getOutputStream().write(bypes);
			}
			//传递参数
			Map<String, List<String>> map = conn.getHeaderFields();
			System.out.println("响应码:"+conn.getResponseCode());
			returnMap.put("statusCode", conn.getResponseCode()+"");
			
			for (String key : map.keySet()) {
			    System.out.println("响应key:"+key);
			    if(map.get(key)!=null){
			    	System.out.println("响应value:"+map.get(key).get(0));
			    	if("WWW-Authenticate".equals(key)){
			    		String responStr = map.get(key).get(0).replaceAll("Digest", "").replaceAll(" ", "");
			    		if(responStr.indexOf("\r\n")!=-1){
			    			System.out.println("有换行");
			    		}else{
			    			System.out.println("无换行");
			    		}
			    		String[] arr = responStr.split(",");
			    		for (int i = 0; i < arr.length; i++) {
							if(arr[i].indexOf("realm=")!=-1){
								String realm = arr[i].replaceAll("realm=", "").replaceAll("\"", "");
								returnMap.put("realm", realm);
								System.out.println("realm:"+realm);
							}else if(arr[i].indexOf("qop=")!=-1){
								String qop = arr[i].replaceAll("qop=", "").replaceAll("\"", "");
								returnMap.put("qop", qop);
								System.out.println("qop:"+qop);
							}else if(arr[i].indexOf("nonce=")!=-1){
								String nonce = arr[i].replaceAll("nonce=", "").replaceAll("\"", "");
								returnMap.put("nonce", nonce);
								System.out.println("nonce:"+nonce);
							}
						}
			    	}
			    }else{
			    	System.out.println("响应value:null");
			    }
			}
		return returnMap;
	
	}

/**
	 * 
	 * @param url
	 * @param method
	 * @param param
	 * @throws IOException 
	 */
	public static String restConnectForSecond(String url,String method,String param,String authentication) throws IOException {
		URL restUrl=new URL(url);
		HttpURLConnection conn = (HttpURLConnection) restUrl.openConnection(); 
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setRequestMethod(method);
		conn.setUseCaches(false);
//		conn.setRequestProperty("Accept-Charset", "UTF-8");
//			conn.setRequestProperty("contentType", "UTF-8");	
		//设置访问提交模式,表单提交  
//		conn.setRequestProperty("accept","application/json1");
		conn.setRequestProperty("Content-Type","application/json");
		conn.setRequestProperty("Authorization",authentication);
		conn.setConnectTimeout(10000);//连接超时 单位毫秒
		conn.setReadTimeout(5000);//读取超时 单位毫秒
		//传递参数
		if (param != null && !"".equals(param)) {
			byte[] bypes = param.toString().getBytes("utf-8");
			conn.getOutputStream().write(bypes);
		}
		InputStream inStream=conn.getInputStream();	
		byte[] buffer = new byte[10240];
	    int length = 0;
	    String strResult = "";
		while ((length = inStream.read(buffer)) != -1) {
			strResult += new String(buffer,0,length,"utf-8");
			
		}
		System.out.println("strResult:="+strResult);
		//传递参数
		System.out.println("reponse:="+conn.getResponseMessage());
		System.out.println("reponcode:="+conn.getResponseCode());
		return  conn.getResponseCode()+"";
		
	}
	public static String restConnect(String url,String method,String param,String authentication) {
		String strResult="";
		try {
			URL restUrl=new URL(url);
			HttpURLConnection conn = (HttpURLConnection) restUrl.openConnection(); 
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestMethod(method);
			conn.setUseCaches(false);
//			conn.setRequestProperty("Accept-Charset", "UTF-8");	
//			conn.setRequestProperty("contentType", "UTF-8");	
				//设置访问提交模式,表单提交  
			conn.setRequestProperty("Content-Type","application/viid+json");
			conn.setRequestProperty("User-Identify",authentication);
			conn.setConnectTimeout(10000);//连接超时 单位毫秒  
			conn.setReadTimeout(5000);//读取超时 单位毫秒
			//传递参数
			if (param != null && !"".equals(param)) {
				byte[] bypes = param.toString().getBytes("utf-8");  
				conn.getOutputStream().write(bypes);
			}
			InputStream inStream=conn.getInputStream();	
			byte[] buffer = new byte[10240];
		    int length = 0;
			while ((length = inStream.read(buffer)) != -1) {
				strResult += new String(buffer,0,length,"utf-8");
				
			}
//			BufferedReader br = new BufferedReader(new InputStreamReader(inStream));
//			strResult =  new String(br.readLine().getBytes(), "utf-8") ;  // 读取一行数据
			
//			System.out.println(strResult);
//			System.out.println(inStream.available());
//			byte[] bytes = new byte[inStream.available()];		
//			inStream.read(bytes, 0, inStream.available());		
//			int responseCode = conn.getResponseCode(); 
//			strResult = new String(bytes,"utf-8");
//			System.out.println(strResult);
//			System.out.println(strResult.length());
//			System.out.println(inStream.available());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strResult;
	}

	public static void testPerson(){
		
	}

MD5加密

public class Md5Utils
{
    private static final Logger log = LoggerFactory.getLogger(Md5Utils.class);
    private static final int HEX_VALUE_COUNT = 16;
    private static byte[] md5(String s)
    {
        MessageDigest algorithm;
        try
        {
            algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(s.getBytes("UTF-8"));
            byte[] messageDigest = algorithm.digest();
            return messageDigest;
        }
        catch (Exception e)
        {
            log.error("MD5 Error...", e);
        }
        return null;
    }

    private static final String toHex(byte hash[])
    {
        if (hash == null)
        {
            return null;
        }
        StringBuffer buf = new StringBuffer(hash.length * 2);
        int i;

        for (i = 0; i < hash.length; i++)
        {
            if ((hash[i] & 0xff) < 0x10)
            {
                buf.append("0");
            }
            buf.append(Long.toString(hash[i] & 0xff, 16));
        }
        return buf.toString();
    }

    public static String hash(String s)
    {
        try
        {
            return new String(toHex(md5(s)).getBytes("UTF-8"), "UTF-8");
        }
        catch (Exception e)
        {
            log.error("not supported charset...{}", e);
            return s;
        }
    }
    public static String getMD5(byte[] bytes) {
        char[] hexDigits = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        char[] str = new char[32];

        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(bytes);
            byte[] tmp = md.digest();
            int k = 0;

            for(int i = 0; i < 16; ++i) {
                byte byte0 = tmp[i];
                str[k++] = hexDigits[byte0 >>> 4 & 15];
                str[k++] = hexDigits[byte0 & 15];
            }
        } catch (Exception var8) {
            var8.printStackTrace();
        }

        return new String(str);
    }

    public static String getMD5(String value, String encode) {
        String result = "";

        try {
            result = getMD5(value.getBytes(encode));
        } catch (UnsupportedEncodingException var4) {
            var4.printStackTrace();
        }

        return result;
    }
}

大功告成

### 回答1: GAT1400协议是一种通信协议,用于在计算机和其他设备之间传递数据。GAT1400协议有一个注册保活功能,可以帮助维护设备之间的连接,避免连接中断。 下面是一个示例代码,用于在使用GAT1400协议的视图库中实现注册保活功能: ``` while True: # 发送注册保活报文 send_keepalive_packet() # 等待响应 response = wait_for_response() if response == TIMEOUT: # 如果超时,重新发送注册保活报文 continue elif response == ERROR: # 如果收到错误响应,则断开连接 break else: # 如果收到正确响应,则继续等待下一次响应 continue ``` 在上面的代码中,`send_keepalive_packet()` 函数用于发送注册保活报文,`wait_for_response()` 函数用于等待响应。如果收到正确的响应,则继续等待下一次响应;如果超时或收到错误响应,则会重新发送注册保活报文或断开连接。 请注意,上面的代码仅是一个示例,具体实现方式可能因视图库版本和使用的编程语言而异。 ### 回答2: 视图库GAT1400协议的注册保活代码是为了确保视图库能够在注册后保持与服务器的连接。以下是一个简单的示例代码: ``` import gat1400 # 创建视图库对象 view_lib = gat1400.ViewLibrary() # 设置服务器信息 server_address = "192.168.1.100" server_port = 8080 view_lib.set_server(server_address, server_port) # 注册保活函数 def keep_alive(): # 在这里实现与服务器保活的逻辑 # 这里可以发送心跳包或者定期向服务器发起请求来保持连接 # 示例代码中使用定时器每隔30秒发起一次请求 view_lib.request_keep_alive() t = threading.Timer(30, keep_alive) t.start() # 注册保活 def pre_register(): # 在这里实现注册保活的逻辑 # 这里可以发送心跳包或者定期向服务器发起请求来保持连接 # 示例代码中使用定时器每隔15秒发起一次请求 view_lib.request_pre_register() t = threading.Timer(15, pre_register) t.start() # 注册保活函数 keep_alive() # 注册保活函数 pre_register() # 注册 view_lib.register() ``` 上述代码中,我们首先导入gat1400视图库模块,创建一个视图库对象(view_lib),然后设置服务器的IP地址和端口号。接下来定义了一个保活函数(keep_alive),用于保持与服务器的连接。在保活函数中,我们可以实现向服务器发送心跳包或者定期向服务器发起请求的逻辑,这里使用定时器每隔30秒向服务器发送请求。然后定义了一个注册保活函数(pre_register),用于注册前的保持连接,同样使用定时器每隔15秒向服务器发送请求。最后,我们调用视图库对象的register()方法完成注册过程。这样,注册保活的代码就完成了。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值