本文提供RPA 服務端API的Python語言調用示例與Java語言調用示例。
配置訪問憑證
重要
調用接口前,需要配置環境變量,通過環境變量讀取訪問憑證。關于配置環境變量的操作,
機器人流程自動化的AccessKey ID和AccessKey Secret的環境變量名:RPA_AK_ENV 、RPA_SK_ENV。
Linux和macOS系統配置方法
執行以下命令:
export RPA_AK_ENV =<access_key_id>
export RPA_SK_ENV=<access_key_secret>
<access_key_id>
需替換為已準備好的AccessKey ID,<access_key_secret>
替換為AccessKey Secret。
Windows系統環境變量配置方法
右擊我的電腦,選擇屬性
在彈出的窗口中選擇高級系統設置
點擊系統屬性中的高級,選擇環境變量
在系統變量中添加環境變量名為RPA_AK_ENV 、RPA_SK_ENV,并寫入從RPA控制臺的系統設置頁面獲取的AK信息。
重啟電腦
調用示例
Python調用示例
import requests import base64 import datetime import hmac import random from hashlib import sha1 from urllib import parse import json import os def start(): # 以獲取客戶端信息接口為例 # 用戶私鑰 AccessSecret = os.getenv('RPA_SK_ENV') # 請求方式 method = 'POST' # 公共請求參數 AccessKeyId = os.getenv('RPA_AK_ENV') signature_method = "HMAC-SHA1" signature_version = "1.0" signature_nonce = ''.join(random.sample('abcdefghijklmnopqrstuvwxyz', 26)) timestamp = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ") version = "20200430" data_format = "json" # 接口獨有的請求參數 appId = "應用id" clientId = "機器人id" appParams= json.dumps([{"name": "示例參數1", "value": "示例內容1"},{"name": "示例參數2", "value": "示例內容2"}]) params = {"AccessKeyId": AccessKeyId, "Format": data_format, "SignatureMethod": signature_method, "SignatureNonce": signature_nonce, "SignatureVersion": signature_version, "Timestamp": timestamp, "Version": version, "appId": appId, "clientId":clientId, "appParams":appParams, } # print(params) # 參與加簽的參數:用戶私鑰、請求方式、公共請求參數、接口獨有的參數 # 步驟一:將公共請求參數以及接口獨有參數進行排序 items = list(params.keys()) items.sort() temp_list = [] for i in items: if i == 'AppParams' or i == 'appParams': temp_list.append(parse.quote(i) + "=" + parse.quote(params[i])) continue temp_list.append(parse.quote_plus(i) + "=" + parse.quote_plus(params[i])) temp_string = "&".join(temp_list) # 步驟二:構造規范化請求字符串 StringToSign = method.upper() + "&%2F&" + parse.quote_plus(temp_string) # print("===============" + StringToSign) # 步驟三:生成簽名參數 h = hmac.new((AccessSecret + '&').encode("utf-8"), StringToSign.encode("utf-8"), sha1).digest() Signature = base64.b64encode(h) # 打印簽名參數 # print(Signature) # 打印其他參數(發送請求時的timestamp以及SignatureNonce參數需要使用) # print(timestamp) # print(signature_nonce) # 創建服務型任務 url = 'https://console-rpa.aliyun.com/rpa/openapi/task/createServiceTask' params['Signature'] = Signature req = requests.post(url=url, data=params) # req = requests.get(url=url,params=params) print(req.json()) if __name__ == '__main__': start()
Java調用示例
package com.company; import sun.misc.BASE64Encoder; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.*; public class Main { /** * 服務器地址(以RPA公有云集群為例) */ public static final String SERVER = "https://console-rpa.aliyun.com"; /** * 調用接口路徑, 以createServiceTask為例 */ public static final String PATH = "/rpa/openapi/task/createServiceTask?"; /** * AKSK */ public static final String ACCESS_KEY_ID = System.getenv("RPA_AK_ENV"); public static final String ACCESS_KEY_SECRET = System.getenv("RPA_SK_ENV"); public static void main(String[] args) { // 接口專有參數 String httpMethod = "POST"; String appId = "應用id"; String clientId = "機器人id"; String appParams = "[{\"name\":\"示例參數1\",\"value\":\"示例內容1\"},{\"name\":\"示例參數2\",\"value\":\"示例內容2\"}]"; Map<String, String> specialParams = new HashMap<>(); specialParams.put("appId", appId); specialParams.put("clientId", clientId); specialParams.put("appParams", appParams); // 調用示例 try { Map<String, String> parameters = new HashMap(); // 公共請求參數 String signatureNonce = UUID.randomUUID().toString(); String timeStamp = formatIso8601Date(new Date()); parameters.put("Version", "20200430"); parameters.put("AccessKeyId", ACCESS_KEY_ID); parameters.put("Timestamp", timeStamp); parameters.put("SignatureMethod", "HMAC-SHA1"); parameters.put("SignatureVersion", "1.0"); parameters.put("SignatureNonce", signatureNonce); parameters.put("Format", "json"); parameters.putAll(specialParams); // 排序請求參數 String[] sortedKeys = parameters.keySet().toArray(new String[]{}); Arrays.sort(sortedKeys); // 構造 stringToSign 字符串 StringBuilder stringToSign = new StringBuilder(); stringToSign.append(httpMethod).append("&"); stringToSign.append(percentEncode("/")).append("&"); // 簽名參數 StringBuilder canonicalizedQueryString = new StringBuilder(); // url公告參數構建 StringBuilder urlParamsBuild = new StringBuilder(); for (String key : sortedKeys) { // 這里注意編碼 key 和 value canonicalizedQueryString.append("&") .append(percentEncode(key)).append("=") .append(percentEncode(parameters.get(key))); urlParamsBuild.append("&") .append(percentEncode(key)).append("=") .append(percentEncode(parameters.get(key))); } stringToSign.append(percentEncode( canonicalizedQueryString.substring(1))); // 計算簽名 Mac mac = Mac.getInstance("HmacSHA1"); mac.init(new SecretKeySpec((ACCESS_KEY_SECRET + "&").getBytes(StandardCharsets.UTF_8), "HmacSHA1")); byte[] signData = mac.doFinal(stringToSign.toString().getBytes(StandardCharsets.UTF_8)); final BASE64Encoder base64Encoder = new BASE64Encoder(); String signature = base64Encoder.encode(signData); String urlReq = urlParamsBuild.substring(1); String url = SERVER + PATH + urlReq + "&Signature=" + percentEncode(signature); String requestResult = restfulReq(url, httpMethod); System.out.println(requestResult); } catch (Exception e) { System.out.println("encode失敗,異常:" + e); } } /** * 發送請求 */ private static String restfulReq(String url, String method) { Map<String, String> params = new HashMap<>(); String result = ""; try { Map<String, String> header = new HashMap<>(); header.put("contentType", "application/json;charset=UTF-8"); if ("POST".equals(method)) { result = doPost(url, header, joinParams(params), method); } if ("GET".equals(method)) { result = doGet(url, header, params, method); } } catch (Exception err) { throw new RuntimeException(err.toString()); } return result; } private static String joinParams(Map<String, String> params) { if (params != null) { String result = ""; StringBuilder sb = new StringBuilder(); Iterator<Map.Entry<String, String>> newEntryIt = params.entrySet().iterator(); while (newEntryIt.hasNext()) { Map.Entry<String, String> entry = newEntryIt.next(); sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&"); } if (sb.toString().endsWith("&")) { result = sb.substring(0, sb.length() - 1); } return result; } return null; } /** * 向指定URL發送POST請求 */ private static String doPost(String url, Map<String, String> header, String param, String method) { DataOutputStream out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 打開和URL之間的連接 HttpURLConnection conn = (HttpURLConnection) realUrl .openConnection(); // 設置通用的請求屬性 conn.setRequestProperty("accept", "*/*"); conn.setRequestMethod(method); Iterator<Map.Entry<String, String>> it = header.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> entry = it.next(); conn.setRequestProperty(entry.getKey(), entry.getValue()); } conn.setUseCaches(false); // 發送POST請求必須設置如下兩行 conn.setDoOutput(true); conn.setDoInput(true); conn.setReadTimeout(6000); conn.setConnectTimeout(6000); // 定義BufferedReader輸入流來讀取URL的響應 try { if (param != null && !"".equals(param.trim())) { out = new DataOutputStream(conn.getOutputStream()); out.write(param.getBytes()); // flush輸出流的緩沖 out.flush(); } in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("異常" + e); } } catch (Exception e) { System.out.println("異常" + e); } // 使用finally塊來關閉輸出流和輸入流 finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { System.out.println("異常--" + ex.getMessage()); } } return result; } /** * 向指定URL發送GET請求 */ private static String doGet(String urlStr, Map<String, String> header, Map<String, String> params, String method) { URL url; HttpURLConnection conn = null; InputStream is = null; ByteArrayOutputStream baos = null; try { // URL傳入參數 String queryString = ""; if (params != null) { for (Map.Entry<String, String> entry : params.entrySet()) { queryString += entry.getKey() + "=" + URLEncoder.encode(entry.getValue().toString(), "UTF-8") + "&"; } } if (queryString.length() > 0) { queryString = queryString .substring(0, queryString.length() - 1); urlStr = urlStr + "?" + queryString; } url = new URL(urlStr); conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(6000); conn.setConnectTimeout(6000); conn.setRequestMethod(method); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("Accept-Charset", "UTF-8"); conn.setRequestProperty("contentType", "application/json;charset=utf-8"); Iterator<Map.Entry<String, String>> it = header.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> entry = it.next(); conn.setRequestProperty(entry.getKey(), entry.getValue()); } if (conn.getResponseCode() == 200) { is = conn.getInputStream(); baos = new ByteArrayOutputStream(); int len = -1; byte[] buf = new byte[128]; while ((len = is.read(buf)) != -1) { baos.write(buf, 0, len); } baos.flush(); return baos.toString(); } else { throw new RuntimeException(conn.getResponseCode() + ":" + conn.getResponseMessage()); } } catch (Exception e) { throw new RuntimeException(e.toString()); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { System.out.println("異常" + e); } try { if (baos != null) { baos.close(); } } catch (IOException e) { System.out.println("異常" + e); } conn.disconnect(); } } private static String percentEncode(String value) throws UnsupportedEncodingException { return value != null ? URLEncoder.encode(value, "UTF-8").replace("+", "%20").replace("*", "%2A").replace("%7E", "~") : null; } private static String formatIso8601Date(Date date) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); df.setTimeZone(new SimpleTimeZone(0, "GMT")); return df.format(date); } }
文檔內容是否對您有幫助?