CKafka系列学习文章 - 用java实现API调用(十一)

2019-09-16 11:12:59 浏览数 (1)

导语:上一章节我们了解了怎么手动拼接请求URL和用API2.0签名自动生成请求URL,来调用CKafka的接口,这一章将进入开发阶段,用java实现拼接请求URL,进行API调用。

一、申请安全凭证

在第一次使用腾讯云 API 之前,用户需要在【腾讯云控制台】> 【API 密钥管理 】上申请安全凭证。安全凭证包括 SecretId 和 SecretKey,其中:

  • SecretId:用于标识 API 调用者身份。
  • SecretKey:用于加密签名字符串和服务器端验证签名字符串的密钥。

注意: API 密钥是构建腾讯云 API 请求的重要凭证,使用腾讯云 API 可以操作您名下的所有腾讯云资源,为了您的财产和服务安全,请妥善保存并定期更换密钥,当您更换密钥后,请及时删除旧密钥。

二、生成签名串请求参数 (Signature)

1. 对参数排序

代码语言:javascript复制
	/* 对参数排序 方法一*/
    public static String mapSortedByKey(Map<String, String> param) {
        StringBuilder stringBuilder = new StringBuilder();
        ArrayList<String> keyList = new ArrayList<>(param.keySet());
        Collections.sort(keyList);
        for (int i = 0; i < keyList.size(); i  ) {
            String key = keyList.get(i);
            if (i == keyList.size() - 1) {
                stringBuilder.append(key).append("=").append(param.getOrDefault(key, ""));
            } else {
                stringBuilder.append(key).append("=").append(param.getOrDefault(key, "")).append("&");
            }
        }
        return stringBuilder.toString();
    }
    /* 对参数排序 方法二*/
    public static void sortMap(Map<String, String> param) {
        TreeMap<String, String> paramTreeMap = new TreeMap<>(param);
        System.out.println(paramTreeMap);
    }

2. 拼接签名原文字符串

代码语言:javascript复制
	/* 拼接请求URL */
    public static String getRqstUrl(String method, List list) {
        StringBuilder builder = new StringBuilder();
        boolean isFirst = true;
        builder.append(method);
        for (int i=0;i<list.size();i  ) {
        	    if(i==0) {
        	    	builder.append(list.get(i));
        	    }else if (i==1) {
                    builder.append("?");
                    builder.append(list.get(i));
                }else {
                    builder.append("&");
                    builder.append(list.get(i));
                }
        }
        return builder.toString();
    }

3. 生成签名串

代码语言:javascript复制
	/* 生成签名串 */
   public static String sha256_HMAC(String message, String secret) { 
    	String hash="";
    	try {
    	   Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
	       SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
	       sha256_HMAC.init(secret_key);
	       hash = Base64.encodeBase64String(sha256_HMAC.doFinal(message.getBytes()));
	       System.out.println(hash);
	    }
	    catch (Exception e){
	       System.out.println("Error");
	    }
    	return hash;
    } 
    

三、签名串URL编码

代码语言:javascript复制
/* URL 编码: */
   public static String getURLEncoderString(String str) {
      String result = "";
      if (null == str) {
          return "";
      }
      try {
          result = java.net.URLEncoder.encode(str, "UTF-8");
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }
      return result;
   }

	/* URL 解码: */
   public static String URLDecoderString(String str) {
      String result = "";
      if (null == str) {
          return "";
      }
      try {
          result = java.net.URLDecoder.decode(str, "UTF-8");
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }
      return result;
  }

四、调用GET方式请求URL

代码语言:javascript复制
/* 执行URL请求 */
    public static String sendGet(String url) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url;
            URL realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.connect();
            Map<String, List<String>> map = connection.getHeaderFields();
            for (String key : map.keySet()) {
                System.out.println(key   "--->"   map.get(key));
            }
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result  = line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

五、调用获取主题列表接口

代码语言:javascript复制
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class ToInterface {
	
	private final static String secretId="AKIDKTM0OYJ6SaaKnyxxxxxxxxxxxxxxxxx";
	private final static String secretKey="WmmW0wd4E8nCKEPxxxxxxxxxxxxxxx";  
	
	/* main方法 */
    public static void main(String[] args) {
    	int times=(int) (System.currentTimeMillis()/1000);
    	String timestamp=String.valueOf(times);
    	String nonce=timestamp;
    	//获取消费分组 offset接口 
    	//String str3=GetGroupOffsets(nonce,timestamp);
      //调用获取主题列表接口
    	String str3=GetListTopic(nonce,timestamp);
    	System.out.println(str3);
        
    }
     //获取主题列表接口
    public static String GetListTopic(String nonce,String timestamp) {
    	String url="ckafka.api.zijiebao.com/v2/index.php";
    	String signatureMethod="HmacSHA256";
    	String instanceId="ckafka-3vekxxxx";
    	Map<String, String> param = new HashMap<>();
        param.put("Action", "ListTopic");
        param.put("Nonce", nonce);
        param.put("instanceId",instanceId);
        param.put("Timestamp",timestamp);
        param.put("SignatureMethod", signatureMethod);
        param.put("Region", "ap-guangzhou");
        param.put("SecretId", secretId);
    	return getResult(param,url);
    }
    /* 获取消费分组 offset接口 */
    public static String GetGroupOffsets(String nonce,String timestamp) {
    	
    	String url="ckafka.api.zijiebao.com/v2/index.php";
    	String signatureMethod="HmacSHA256";
    	String instanceId="ckafka-3vekxxxx";
    	Map<String, String> param = new HashMap<>();
        param.put("Action", "GetGroupOffsets");
        param.put("Nonce", nonce);
        param.put("instanceId",instanceId);
        param.put("Timestamp",timestamp);
        param.put("SignatureMethod", signatureMethod);
        param.put("Region", "ap-guangzhou");
        param.put("SecretId", secretId);
        param.put("group", "console-consumer-2529");
        
    	return getResult(param,url);
    }

	/* 执行调用 */
   public static String getResult(Map<String, String> param,String url) {
	   
	   String strparam=mapSortedByKey(param);
       List list=new ArrayList();
       list.add(url);
       list.add(strparam);
       //System.out.println(list.get(0));
       String str=getRqstUrl("GET",list);
       System.out.println(str);

       String signature1= getURLEncoderString(sha256_HMAC(str,secretKey));
		
       list.add("Signature=" signature1);
       String str2=getRqstUrl("https://",list);
       String str3 =sendGet(str2);
       return str3;
   }

	
}

执行结果:有3个topic,显示有topicId和topicName、note

代码语言:javascript复制
{"code":0,"message":"","codeDesc":"Success",
"data":{"totalCount":3,"topicList":[
{"topicId":"topic-7p2pzlo4","topicName":"topic_test1","note":""},
{"topicId":"inter-topic-kfjiqvgo","topicName":"bowenqiu_test1","note":""},
{"topicId":"topic-3yueh1ge","topicName":"bowenqiu_topic1","note":"bowenqiu_topic1"}]}}

0 人点赞