非sdk调用奇门接口

话不多说,直接上代码!

/**
 * 
* <p>Title: QiMenUtils</p>  
* 奇门加密工具类
* @author huangsq  
* @date 2018年11月4日
 */
public class QiMenUtils {

    public static void main(String[] args) throws UnsupportedEncodingException {
         String host = "qimenapi.tbsandbox.com:80/router/qimen/service";
         //String host = "gw.api.tbsandbox.com/router/rest";
         String appkey = "1025167800";
         //String appkey = "testerp_appkey";
         
         String secret = "sandbox2b05dad04e4e68e676cbb9bf0";
         String method = "taobao.qimen.returnorder.confirm";
         //String method = "taobao.times.get";
         //String method = "taobao.qimen.transferorder.report";
         
         String customerId = "c1540886273807";
         //String customerId = "stub-cust-code";
         
         //String body = "";
         String file = "f:/qimen2.txt";
         String body = getFileString(file);
         SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         String timestamp = "2018-11-08 08:08:08";
         StringBuffer url = new StringBuffer();
         StringBuffer url1 = new StringBuffer();
         url.append("http://"+host+
                  "?method="+method+
                 "&timestamp="+timestamp+
                "&format=xml"+
                "&app_key="+appkey+
                "&v=2.0"+
                "&sign_method=md5"+
                "&customerId="+customerId);
         QiMenUtils qiMenUtils = new QiMenUtils();
         String signs = qiMenUtils.sign(url.toString(), body, secret);
         url1.append("http://"+host+
                  "?method="+method+
                 "&timestamp="+URLEncoder.encode( timestamp,"utf-8")+
                "&format=xml"+
                "&app_key="+appkey+
                "&v=2.0"+
                "&sign_method=md5"+
                "&sign="+signs+
                "&customerId="+customerId
                );
         String[] urls1 = url1.toString().split("\\?");
         System.out.println("?" + urls1[1]);
         String result = "";
            BufferedReader in = null;
            PrintWriter out = null;
         try {
         URL realUrl = new URL(url1.toString());
        // 打开和URL之间的连接
         URLConnection conn = realUrl.openConnection();
         // 设置通用的请求属性
         conn.setRequestProperty("accept", "*/*");
         conn.setRequestProperty("connection", "Keep-Alive");
         conn.setRequestProperty("user-agent",
                 "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
         conn.setRequestProperty("Content-Type","application/xml; charset=utf-8");
         // 发送POST请求必须设置如下两行
         conn.setDoOutput(true);
         conn.setDoInput(true);
         // 获取URLConnection对象对应的输出流
         out = new PrintWriter(conn.getOutputStream());
         // 发送请求参数
         out.print(body);
         // flush输出流的缓冲
         out.flush();
         // 定义BufferedReader输入流来读取URL的响应
         in = new BufferedReader(
                 new InputStreamReader(conn.getInputStream()));
         String line;
         while ((line = in.readLine()) != null) {
             result += line;
         }
     } catch (Exception e) {
         System.out.println("发送GET请求出现异常!" + e);
         e.printStackTrace();
     }
     // 使用finally块来关闭输入流
     finally {
         try {
             if (in != null) {
                 in.close();
             }
         } catch (Exception e2) {
             e2.printStackTrace();
         }
     }
         System.out.println("result="+result);
    }
 
    
    public String sign(String url, String body, String secretKey) {
 
        Map<String, String> params = getParamsFromUrl(url);
 
        // 1. 第一步,确保参数已经排序
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);
 
        // 2. 第二步,把所有参数名和参数值拼接在一起(包含body体)
        String joinedParams = joinRequestParams(params, body, secretKey, keys);
 
        //your_secretKeyapp_keyyour_appkeycustomerIdyour_customerIdformatxmlmethodyour_methodsign_methodmd5timestamp2015-04-26 00:00:07vyour_versionyour_bodyyour_secretKey
        System.out.println(joinedParams);
 
        // 3. 第三步,使用加密算法进行加密(目前仅支持md5算法)
        String signMethod = params.get("sign_method");
        if (!"md5".equalsIgnoreCase(signMethod)) {
            return null;
        }
        byte[] abstractMesaage = digest(joinedParams);
 
        // 4. 把二进制转换成大写的十六进制
        String sign = byte2Hex(abstractMesaage);
 
        return sign;
 
    }
 
    private Map<String, String> getParamsFromUrl(String url) {
        Map<String, String> requestParams = new HashMap<String, String>();
        try {
            String fullUrl = URLDecoder.decode(url, "UTF-8");
            String[] urls = fullUrl.split("\\?");
            if (urls.length == 2) {
                String[] paramArray = urls[1].split("&");
                for (String param : paramArray) {
                    String[] params = param.split("=");
                    if (params.length == 2) {
                        requestParams.put(params[0], params[1]);
                    }
                }
            }
        } catch (UnsupportedEncodingException e) {
        }
        return requestParams;
    }
 
    private String byte2Hex(byte[] bytes) {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        int j = bytes.length;
        char str[] = new char[j * 2];
        int k = 0;
        for (byte byte0 : bytes) {
            str[k++] = hexDigits[byte0 >>> 4 & 0xf];
            str[k++] = hexDigits[byte0 & 0xf];
        }
        return new String(str);
    }
 
    private byte[] digest(String message)  {
        try {
            MessageDigest md5Instance = MessageDigest.getInstance("MD5");
            md5Instance.update(message.getBytes("UTF-8"));
            return md5Instance.digest();
        } catch (UnsupportedEncodingException e) {
            return null;
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }
 
    private String joinRequestParams(Map<String, String> params, String body, String secretKey, String[] sortedKes) {
        StringBuilder sb = new StringBuilder(secretKey); // 前面加上secretKey
 
        for (String key : sortedKes) {
            if ("sign".equals(key)) {
                continue; // 签名时不计算sign本身
            } else {
                String value = params.get(key);
                if (isNotEmpty(key) && isNotEmpty(value)) {
                    sb.append(key).append(value);
                }
            }
        }
        sb.append(body); // 拼接body体
        sb.append(secretKey); // 最后加上secretKey
        return sb.toString();
    }
 
    private boolean isNotEmpty(String s) {
        return null != s && !"".equals(s);
    }
    
public static String getFileString(final String path){
        
        File msgFile = new File(path);
        StringBuilder txtAll = new StringBuilder();
        try{
            if(msgFile.isFile() && msgFile.exists()){
                InputStreamReader reader = new InputStreamReader(new FileInputStream(msgFile),"UTF-8");
                BufferedReader breader = new BufferedReader(reader);
                String txtValue = "";
                while((txtValue = breader.readLine()) != null){
                    txtAll.append(txtValue);                    
                }
                
                reader.close();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        
        return txtAll.toString();
    }
}

猜你喜欢

转载自www.cnblogs.com/ziyanxiaoxiang/p/9928956.html