API调用方法详解 

 

1.API签名算法

  • API2.0签名算法描述:

    API调用,参数sign动态生成规则:
    • 1、拼装

    根据参数名称将你的所有请求参数按照字母先后顺序排序:key + value .... key + value
    value对是除签名和图片外的所有请求参数按key做的升序排列, value无需编码。
    例如将foo=1,bar=2,baz=3 排序为bar=2,baz=3,foo=1
    参数名和参数值链接后,得到拼装字符串bar2baz3foo1
    • 2、签名(utf-8编码)

    2-1、md5:将secret同时拼接到参数字符串头、尾部进行md5加密,格式是:byte2hex(md5(secretkey1value1key2value2...secret))。
    注:byte2hex为自定义方法,目的是将二进制转16进制
    • 3、示例(根据下面示例参数生成的sign跟它一模一样就说明签名算法是正确的):

    3-1、不需要sessionKey的例子:
    参数:
    appKey:10210015121700112233、format:json、ver:1.0、method:yhd.sby.user.get、timestamp:2015-12-17 10:00:00、merchantId:12345、appSecret:APPSECRETFORLIUYUETOTEST01234567
     
    组装进行加密的串:
    APPSECRETFORLIUYUETOTEST01234567appKey10210015121700112233formatjsonmerchantId12345methodyhd.sby.user.get
    timestamp2015-12-17 10:00:00ver1.0APPSECRETFORLIUYUETOTEST01234567
     
    加密后生成的sign:ab8b16aa5308042a0ab4c647c9ac45db
     
    3-2、需要sessionKey的例子:
    参数:
    appKey:10210015121700112233、sessionKey:SESSIONKEYFORLIUYUETOTEST0123456、format:json、ver:1.0、
    method:yhd.category.brands.get、timestamp:2015-12-17 10:00:00、appSecret:APPSECRETFORLIUYUETOTEST01234567
     
    组装进行加密的串:
    APPSECRETFORLIUYUETOTEST01234567appKey10210015121700112233formatjsonmethodyhd.category.brands.get
    sessionKeySESSIONKEYFORLIUYUETOTEST0123456timestamp2015-12-17 00:00:00
    ver1.0APPSECRETFORLIUYUETOTEST01234567
     
    加密后生成的sign:72c33f6b5c2d555b3527e510ade690cd
  • MD5算法代码片段:

    /**
    * 新的md5签名,首尾放secret。
    *
    * @param params 传给服务器的参数
    *
    * @param secret 分配给您的APP_SECRET
    */
    public static String md5Signature(TreeMap<String, String> params, String secret) {
         String result = null;
         StringBuffer orgin = getBeforeSign(params, new StringBuffer(secret));
         if (orgin == null)
             return result;
     
         // secret last
         orgin.append(secret);
         try {
             MessageDigest md = MessageDigest.getInstance("MD5");
             result = byte2hex(md.digest(orgin.toString().getBytes("utf-8")));
     
         } catch (Exception e) {
             throw new java.lang.RuntimeException("sign error !");
         }
         return result;
    }
     
     
    /**
    * 二进制转字符串
    */
    private static String byte2hex(byte[] b) {
     
         StringBuffer hs = new StringBuffer();
         String stmp = "";
         for (int n = 0; n < b.length; n++) {
             stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
             if (stmp.length() == 1)
             hs.append("0").append(stmp);
             else
             hs.append(stmp);
         }
         return hs.toString();
    }
     
    /**
    * 添加参数的封装方法
    * @param params
    * @param orgin
    * @return
    */
    private static StringBuffer getBeforeSign(TreeMap<String, String> params, StringBuffer orgin) {
         if (params == null)
             return null;
         Map<String, String> treeMap = new TreeMap<String, String>();
         treeMap.putAll(params);
         Iterator<String> iter = treeMap.keySet().iterator();
         while (iter.hasNext()) {
             String name = (String) iter.next();
             orgin.append(name).append(params.get(name));
         }
     
         return orgin;
    }

2.接口示例代码

示例代码

	/**
	 * xml格式的测试代码
	 * 
	 */
	public void testForXml() {
		//测试环境URL
		String routerUrl = "http://119.97.231.228:2001/app/api/rest/router";
		//测试环境密钥
		String secretKey = "1234567890";
		
		Map<String, String> paramMap = new HashMap<String, String>();
		// 系统级参数设置(必须)
		Date currentTime = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String timestamp = format.format(currentTime);
		paramMap.put("appKey", "abc");
		paramMap.put("sessionKey", "der");
		paramMap.put("timestamp", timestamp);
		paramMap.put("format", "xml");
		paramMap.put("method", "yhd.general.products.search");
		paramMap.put("ver", "1.0");

		// 应用级参数设置(不同接口都不同,具体参考接口详情)
		paramMap.put("pageRows", "100");

		String response = PostClient.sendByPost(paramMap, secretKey, routerUrl);

		System.out.println(response);

	}
	


	//**********************************
	//		发送请求客户端代码
	//**********************************

	package com.yhd.openapi.client;
	
	import java.io.BufferedReader;
	import java.io.InputStream;
	import java.io.InputStreamReader;
	import java.util.ArrayList;
	import java.util.Iterator;
	import java.util.List;
	import java.util.Map;
	import java.util.TreeMap;
	import org.apache.http.HttpEntity;
	import org.apache.http.HttpResponse;
	import org.apache.http.NameValuePair;
	import org.apache.http.client.HttpClient;
	import org.apache.http.client.entity.UrlEncodedFormEntity;
	import org.apache.http.client.methods.HttpPost;
	import org.apache.http.impl.client.DefaultHttpClient;
	import org.apache.http.message.BasicNameValuePair;
	import com.yihaodian.merchant.common.util.Md5Util;
	
	public class PostClient {
	
		private static String POST_URL = "http://openapi.yhd.com/app/api/rest/router";
		
		public static String sendByPost(Map<String, String> appParamMap, String secretKey, String urlStr ) {
			try {
	
				HttpClient httpClient = new DefaultHttpClient();
				if(urlStr == null || urlStr.trim().length() == 0){
					urlStr = POST_URL ;
				}
				
				HttpPost httpPost = new HttpPost(urlStr);
	
				TreeMap<String, String> treeMap = new TreeMap<String, String>();
				if (appParamMap != null) {
					treeMap.putAll(appParamMap);
				}
	
				String sign = Md5Util.md5Signature(treeMap, secretKey);
				treeMap.put("sign", sign);
				Iterator<String> iterator = treeMap.keySet().iterator();
				
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				
				while (iterator.hasNext()) {
					String key = iterator.next();
					params.add(new BasicNameValuePair(key, treeMap.get(key)));
				}
	
				UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(params, "UTF-8");
				httpPost.setEntity(uefEntity);
	
				HttpResponse response = httpClient.execute(httpPost);
				HttpEntity httpEntity = response.getEntity();
				InputStream inputStream = httpEntity.getContent();
	
				//获取返回的数据信息
				StringBuffer postResult = new StringBuffer();
				String readLine = null ;
				BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
				while ((readLine = reader.readLine()) != null) {
					postResult.append(readLine);
				}
	
				httpClient.getConnectionManager().shutdown();
	
				return postResult.toString();
	
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}
	}
 

 

提示

关闭