联系我们:4001526001 创客中心 代理中心 会员登录

Java对接开关demo

这是一个Java版本的demo,用于对接开关的API接口,可以控制开关的开和关,还有获取开关的状态数据传输过程使用discuz加解密方法,个人密匙可以自己配置

1.demo文件

package com.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;

public class Demo {
	 public static String KEY = "d0d3d5b5466cc1ee89eb808de9f5672d";//个人密匙
	 public static String MID = "5b53a2d341d78427feafeb4520bf41eb";//设备密匙
	 public static String URL = "https://wx663ca7ac2632b137.vip.aoyacms.com/plugin/aoya/iot/api.php";//接口地址
 	
	
	 public static void main(String[] args) {
		 long t =  System.currentTimeMillis()/1000;//当前时间秒数
		 Map<String, String> info = new HashMap<String, String>();
		 info.put("act", "switch");//操作信息 switch 操作开关,getState获取开关状态
		 String json = JSON.toJSONString(info);
		 String ciphertext = AuthCode.Encode(json,KEY);//json格式操作信息 authcode加密
		 String check = Md5.MD5(t + MID + ciphertext);//md5字符串加密验证
		 ciphertext = ciphertext.replace("+", "%2B");
		 Map<String, String> map = new HashMap<String, String>();
		 map.put("t", String.valueOf(t));
		 map.put("ciphertext", ciphertext);
		 map.put("mid", MID);
		 map.put("check", check);
		 String result = httpPost(URL,map);
		 System.out.println(result);//打印返回信息
         
         
	}
	//post提交方法
	public static String httpPost(String urlStr,Map<String,String> params){
        URL connect;
        StringBuffer data = new StringBuffer();  
        try {  
           connect = new URL(urlStr);  
           HttpURLConnection connection = (HttpURLConnection)connect.openConnection();  
           connection.setRequestMethod("POST");  
           connection.setDoOutput(true); 
           connection.setDoInput(true);
           connection.setUseCaches(false);//post不能使用缓存
           connection.setInstanceFollowRedirects(true);
           connection.setRequestProperty("accept", "*/*");
           connection.setRequestProperty("connection", "Keep-Alive");
           connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
           OutputStreamWriter paramout = new OutputStreamWriter(  
                   connection.getOutputStream(),"UTF-8"); 
           String paramsStr = "";   //拼接Post 请求的参数
           for(String param : params.keySet()){
               paramsStr += "&" + param + "=" + params.get(param);
           }  
           if(!paramsStr.isEmpty()){
               paramsStr = paramsStr.substring(1);
           }
           //paramsStr = URLEncoder.encode(paramsStr, "UTF-8");  //输出%C4%E3%BA%C3
           paramout.write(paramsStr);  
           paramout.flush();  
           BufferedReader reader = new BufferedReader(new InputStreamReader(  
                   connection.getInputStream(), "UTF-8"));  
           String line;              
           while ((line = reader.readLine()) != null) {          
               data.append(line);            
           }  
         
           paramout.close();  
           reader.close();  
       } catch (Exception e) {  
           // TODO Auto-generated catch block  
           e.printStackTrace();  
       }  
       return data.toString();
   }
}

2.加解密用md5类

package com.util;

import java.security.MessageDigest;

public class Md5 {
	public final static String MD5(String s){ 
		char hexDigits[] = { 
		'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 
		'e', 'f'}; 
		try { 
		byte[] strTemp = s.getBytes(); 
		MessageDigest mdTemp = MessageDigest.getInstance("MD5"); 
		mdTemp.update(strTemp); 
		byte[] md = mdTemp.digest(); 
		int j = md.length; 
		char str[] = new char[j * 2]; 
		int k = 0; 
		for (int i = 0; i < j; i++) { 
		byte byte0 = md[i]; 
		str[k++] = hexDigits[byte0 >>> 4 & 0xf]; 
		str[k++] = hexDigits[byte0 & 0xf]; 
		} 
		return new String(str); 
		} 
		catch (Exception e){ 
		return null; 
		} 
	}
}

3.加解密用Base64类

package com.util;
/**
 * 
 * JAVA 版的BASE64加密
 * 
 * 标准的Base64加密后的字符串长度可以被4整出,比如:
 * 字符		加密后
 * a		YQ==
 * aa		YWE=
 * aaa		YWFh
 * aaab		YWFhYg==
 * aaabb	YWFhYmI=
 * aaabbb	YWFhYmJi
 * 
 * 一旦加密后的字符能被4整除,就用"="来补充
 * 
 * 本例是在网上找的,原本是标准的,遵照RFC2045~RFC2049规范。
 * 
 * PHP版的BASE64可以解密标准的BASE64密文,也可以解密不带后边"="的密文,为了能解密PHP的BASE64和AuthCode加密。
 * (PHP的AuthCode中也用到了BASE64)我将本类做了修改,使之也可以解密不带"="的BASE64密文。
 * 原理很简单,将密文对4取模("密文"%4),看差即为就补几个"=",然后就得到一个标准的BASE64密文并解之。
 * 
 * 
 * 
 */

import java.io.UnsupportedEncodingException;

public class Base64 {
	
    private static char[] base64EncodeChars = new char[]{
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
            'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
            'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
            'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
            'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
            'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
            'w', 'x', 'y', 'z', '0', '1', '2', '3',
            '4', '5', '6', '7', '8', '9', '+', '/'};

    private static byte[] base64DecodeChars = new byte[]{
            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
            52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
            -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
            15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
            -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
            41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1};

    public static String encode(byte[] data) {
        StringBuffer sb = new StringBuffer();
        int len = data.length;
        int i = 0;
        int b1, b2, b3;
        while (i < len) {
            b1 = data[i++] & 0xff;
            if (i == len) {
                sb.append(base64EncodeChars[b1 >>> 2]);
                sb.append(base64EncodeChars[(b1 & 0x3) << 4]);
                sb.append("==");
                break;
            }
            b2 = data[i++] & 0xff;
            if (i == len) {
                sb.append(base64EncodeChars[b1 >>> 2]);
                sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
                sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);
                sb.append("=");
                break;
            }
            b3 = data[i++] & 0xff;
            sb.append(base64EncodeChars[b1 >>> 2]);
            sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
            sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);
            sb.append(base64EncodeChars[b3 & 0x3f]);
        }
        return sb.toString();
    }

    public static byte[] decode(String str) throws UnsupportedEncodingException {
    	int remainder = str.length()%4;//对4取模后的余数

    	if(remainder == 2){
    		str = str + "==";
    	}else if(remainder == 3){
    		str = str + "=";
    	}

        StringBuffer sb = new StringBuffer();
        byte[] data = str.getBytes("US-ASCII");
        int len = data.length;
        int i = 0;
        int b1, b2, b3, b4;
        while (i < len) {
           
            do {
                b1 = base64DecodeChars[data[i++]];
            } while (i < len && b1 == -1);
            if (b1 == -1) break;
           
            do {
                b2 = base64DecodeChars
                        [data[i++]];
            } while (i < len && b2 == -1);
            if (b2 == -1) break;
            sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4)));
           
            do {
                b3 = data[i++];
                if (b3 == 61) return sb.toString().getBytes("iso8859-1");
                b3 = base64DecodeChars[b3];
            } while (i < len && b3 == -1);
            if (b3 == -1) break;
            sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));
           
            do {
                b4 = data[i++];
                if (b4 == 61) return sb.toString().getBytes("iso8859-1");
                b4 = base64DecodeChars[b4];
            } while (i < len && b4 == -1);
            if (b4 == -1) break;
            sb.append((char) (((b3 & 0x03) << 6) | b4));
        }
        return sb.toString().getBytes("iso8859-1");
    }

}

4.加解密用Authcode类

package com.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class AuthCode {

	private static String CutString(String str, int startIndex, int length) {
		if (startIndex >= 0) {
			if (length < 0) {
				length = length * -1;
				if (startIndex - length < 0) {
					length = startIndex;
					startIndex = 0;
				} else {
					startIndex = startIndex - length;
				}
			}
			if (startIndex > str.length()) {
				return "";
			}
		} else {
			if (length < 0) {
				return "";
			} else {
				if (length + startIndex > 0) {
					length = length + startIndex;
					startIndex = 0;
				} else {
					return "";
				}
			}
		}
		if (str.length() - startIndex < length) {
			length = str.length() - startIndex;
		}
		return str.substring(startIndex, startIndex + length);
	}

	private static String CutString(String str, int startIndex) {
		return CutString(str, startIndex, str.length());
	}

	static private byte[] GetKey(byte[] pass, int kLen) {
		byte[] mBox = new byte[kLen];
		for (int i = 0; i < kLen; i++) {
			mBox[i] = (byte) i;
		}
		int j = 0;
		for (int i = 0; i < kLen; i++) {
			j = (j + (int) ((mBox[i] + 256) % 256) + pass[i % pass.length])
					% kLen;
			byte temp = mBox[i];
			mBox[i] = mBox[j];
			mBox[j] = temp;
		}
		return mBox;
	}

	private static String RandomString(int lens) {
		char[] CharArray = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k',
				'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
				'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
		int clens = CharArray.length;
		String sCode = "";
		Random random = new Random();
		for (int i = 0; i < lens; i++) {
			sCode += CharArray[Math.abs(random.nextInt(clens))];
		}
		return sCode;
	}

	public static String Encode(String source, String key) {

		try {
			if (source == null || key == null) {
				return "";
			}
			int ckey_length = 4;
			String keya, keyb, keyc, cryptkey;
			key = MD52(key);
			keya = MD52(CutString(key, 0, 16));
			keyb = MD52(CutString(key, 16, 16));
			keyc = ckey_length > 0 ? RandomString(ckey_length) : "";
			cryptkey = keya + MD52(keya + keyc);

			source = "0000000000" + CutString(MD52(source + keyb), 0, 16) + source;
			byte[] temp = RC4(source.getBytes("utf-8"), cryptkey);
			return keyc + Base64.encode(temp);

		} catch (Exception e) {
			return "";
		}	
		
	}

	public static String Decode(String source, String key) {

		try {
			if (source == null || key == null) {
				return "";
			}
			int ckey_length = 4;
			String keya, keyb, keyc, cryptkey, result;
			key = MD52(key);
			keya = MD52(CutString(key, 0, 16));
			keyb = MD52(CutString(key, 16, 16));
			keyc = ckey_length > 0 ? CutString(source, 0, ckey_length) : "";
			cryptkey = keya + MD52(keya + keyc);

			byte[] temp;
			temp = Base64.decode(CutString(source, ckey_length));
			result = new String(RC4(temp, cryptkey));
			if (CutString(result, 10, 16).equals(
					CutString(MD52(CutString(result, 26) + keyb), 0, 16))) {
				return CutString(result, 26);
			} else {
				temp = Base64.decode(CutString(source + "=", ckey_length));
				result = new String(RC4(temp, cryptkey));
				if (CutString(result, 10, 16).equals(
						CutString(MD52(CutString(result, 26) + keyb), 0, 16))) {
					return CutString(result, 26);
				} else {
					temp = Base64.decode(CutString(source + "==", ckey_length));
					result = new String(RC4(temp, cryptkey));
					if (CutString(result, 10, 16)
							.equals(
									CutString(
											MD52(CutString(result, 26) + keyb), 0, 16))) {
						return CutString(result, 26);
					} else {
						return "2";
					}
				}
			}

		} catch (Exception e) {
			return "";
		}

	}

	private static byte[] RC4(byte[] input, String pass) {
		if (input == null || pass == null)
			return null;
		byte[] output = new byte[input.length];
		byte[] mBox = GetKey(pass.getBytes(), 256);
		int i = 0;
		int j = 0;
		for (int offset = 0; offset < input.length; offset++) {
			i = (i + 1) % mBox.length;
			j = (j + (int) ((mBox[i] + 256) % 256)) % mBox.length;
			byte temp = mBox[i];
			mBox[i] = mBox[j];
			mBox[j] = temp;
			byte a = input[offset];
			byte b = mBox[(toInt(mBox[i]) + toInt(mBox[j])) % mBox.length];
			output[offset] = (byte) ((int) a ^ (int) toInt(b));
		}
		return output;
	}

	private static String MD52(String MD5) {
		StringBuffer sb = new StringBuffer();
		String part = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] md5 = md.digest(MD5.getBytes());
			for (int i = 0; i < md5.length; i++) {
				part = Integer.toHexString(md5[i] & 0xFF);
				if (part.length() == 1) {
					part = "0" + part;
				}
				sb.append(part);
			}
		} catch (NoSuchAlgorithmException ex) {
		}
		return sb.toString();
	}

	private static int toInt(byte b) {
		return (int) ((b + 256) % 256);
	}

	public static void main(String[] args) {
		

	}

}

5.maven依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.4</version>
</dependency>

傲亚物联网

物联网

联系我们

400-1526-001

江西省南昌市青山湖区

恒茂梦时代7号楼710

关于我们

维护反馈

我要合作

傲亚CMS

傲亚物联网

开放平台

扫码关注公众号

企业微信服务商 ipv6 ready