客户端请求代码

Java

  1. import java.io.IOException;
  2. import java.net.URLEncoder;
  3. import java.security.MessageDigest;
  4. import java.text.SimpleDateFormat;
  5. import java.util.ArrayList;
  6. import java.util.Collections;
  7. import java.util.Date;
  8. import java.util.HashMap;
  9. import java.util.List;
  10. import java.util.Map;
  11. import java.util.Set;
  12. import org.junit.Test;
  13. import com.alibaba.fastjson.JSON;
  14. import junit.framework.TestCase;
  15. public class PostTest extends TestCase {
  16. @Test
  17. public void testPost() throws IOException {
  18. String appKey = "test";
  19. String secret = "123456";
  20. // 业务参数
  21. Map<String, String> jsonMap = new HashMap<String, String>();
  22. jsonMap.put("goodsName", "iphoneX");
  23. String json = JSON.toJSONString(jsonMap);
  24. json = URLEncoder.encode(json, "utf-8");
  25. // 系统参数
  26. Map<String, Object> param = new HashMap<String, Object>();
  27. param.put("name", "goods.get");
  28. param.put("app_key", appKey);
  29. param.put("data", json);
  30. param.put("timestamp", getTime());
  31. param.put("version", "");
  32. String sign = buildSign(param, secret);
  33. param.put("sign", sign);
  34. System.out.println("=====请求数据=====");
  35. System.out.println(JSON.toJSON(param));
  36. }
  37. /**
  38. * 构建签名
  39. *
  40. * @param paramsMap
  41. * 参数
  42. * @param secret
  43. * 密钥
  44. * @return
  45. * @throws IOException
  46. */
  47. public static String buildSign(Map<String, ?> paramsMap, String secret) throws IOException {
  48. Set<String> keySet = paramsMap.keySet();
  49. List<String> paramNames = new ArrayList<String>(keySet);
  50. Collections.sort(paramNames);
  51. StringBuilder paramNameValue = new StringBuilder();
  52. for (String paramName : paramNames) {
  53. paramNameValue.append(paramName).append(paramsMap.get(paramName));
  54. }
  55. String source = secret + paramNameValue.toString() + secret;
  56. return md5(source);
  57. }
  58. /**
  59. * 生成md5,全部大写
  60. *
  61. * @param message
  62. * @return
  63. */
  64. public static String md5(String message) {
  65. try {
  66. // 1 创建一个提供信息摘要算法的对象,初始化为md5算法对象
  67. MessageDigest md = MessageDigest.getInstance("MD5");
  68. // 2 将消息变成byte数组
  69. byte[] input = message.getBytes();
  70. // 3 计算后获得字节数组,这就是那128位了
  71. byte[] buff = md.digest(input);
  72. // 4 把数组每一字节(一个字节占八位)换成16进制连成md5字符串
  73. return byte2hex(buff);
  74. } catch (Exception e) {
  75. throw new RuntimeException(e);
  76. }
  77. }
  78. /**
  79. * 二进制转十六进制字符串
  80. *
  81. * @param bytes
  82. * @return
  83. */
  84. private static String byte2hex(byte[] bytes) {
  85. StringBuilder sign = new StringBuilder();
  86. for (int i = 0; i < bytes.length; i++) {
  87. String hex = Integer.toHexString(bytes[i] & 0xFF);
  88. if (hex.length() == 1) {
  89. sign.append("0");
  90. }
  91. sign.append(hex.toUpperCase());
  92. }
  93. return sign.toString();
  94. }
  95. public String getTime() {
  96. return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
  97. }
  98. }

JavaScript

  1. /**
  2. //需要发布到服务器上运行,并且server端需要处理跨域
  3. //在IndexController.java上加@CrossOrigin(origins={"*"})
  4. sdk.config({
  5. url : 'http://localhost:8080/api'
  6. ,app_key : 'test'
  7. ,secret : '123456'
  8. ,jwt : 'xxx'
  9. });
  10. sdk.post({
  11. name : 'goods.get' // 接口名
  12. // ,version:'1.0'
  13. // ,access_token:''
  14. ,data : {'goods_name':'iphone'} // 请求参数
  15. ,callback:function(resp) { // 成功回调
  16. console.log(resp)
  17. }
  18. });
  19. sdk.post({
  20. name : 'goods.get' // 接口名
  21. ,data : {'goods_name':'iphone'} // 请求参数
  22. ,callback:function(resp) { // 成功回调
  23. console.log(resp)
  24. }
  25. });
  26. */
  27. ;(function(){
  28. var config = {
  29. url : 'http://127.0.0.1:8080/api'
  30. ,app_key : 'test'
  31. ,secret : '123456'
  32. ,default_version : ''
  33. ,api_name : "name"
  34. ,version_name : "version"
  35. ,app_key_name : "app_key"
  36. ,data_name : "data"
  37. ,timestamp_name : "timestamp"
  38. ,sign_name : "sign"
  39. ,format_name : "format"
  40. ,access_token_name : "access_token"
  41. ,jwt : ''
  42. }
  43. var DEFAULT_FORMAT = 'json';
  44. var UPLOAD_FORM_DATA_NAME = 'body_data';
  45. var CONTENT_TYPE_JSON = 'application/json';
  46. var CONTENT_TYPE_KEY = 'Content-Type';
  47. var POST_TYPE = 'POST';
  48. var GET_TYPE = 'GET';
  49. function copy(source, target) {
  50. if (target && source && typeof source == 'object') {
  51. for (var p in source) {
  52. target[p] = source[p];
  53. }
  54. }
  55. return target;
  56. }
  57. function add0(m){return m<10?'0'+m:m }
  58. function formatDate(time)
  59. {
  60. var y = time.getFullYear();
  61. var m = time.getMonth()+1;
  62. var d = time.getDate();
  63. var h = time.getHours();
  64. var mm = time.getMinutes();
  65. var s = time.getSeconds();
  66. return y+'-'+add0(m)+'-'+add0(d)+' '+add0(h)+':'+add0(mm)+':'+add0(s);
  67. }
  68. /** 构建签名 */
  69. function buildSign(postData,secret) {
  70. var paramNames = [];
  71. for(var key in postData) {
  72. paramNames.push(key);
  73. }
  74. paramNames.sort();
  75. var paramNameValue = [];
  76. for(var i=0,len=paramNames.length;i<len;i++) {
  77. var paramName = paramNames[i];
  78. paramNameValue.push(paramName);
  79. paramNameValue.push(postData[paramName]);
  80. }
  81. var source = secret + paramNameValue.join('') + secret;
  82. // MD5算法参见http://pajhome.org.uk/crypt/md5/
  83. return hex_md5(source).toUpperCase();
  84. }
  85. var ajax = {
  86. /**
  87. * 提交请求
  88. * @param opts.url 请求url
  89. * @param opts.params 请求参数json
  90. * @param opts.headers 请求header,json
  91. * @param opts.form 表单dom对象
  92. * @param opts.callback 回调
  93. * @param opts.error 错误回调
  94. */
  95. request:function(opts) {
  96. var url = opts.url;
  97. var params = opts.params;
  98. var headers = opts.headers;
  99. var form = opts.form;
  100. var callback = opts.callback;
  101. var error = opts.error || function(e){alert('数据请求失败')};
  102. var method = opts.method;
  103. var paramStr = JSON.stringify(params);
  104. var xhr = this.createXhrObject();
  105. xhr.onreadystatechange = function() {
  106. var jsonData = '';
  107. if (xhr.readyState == 4){
  108. var status = xhr.status;
  109. if ((status >= 200 && status < 300) || status == 304){
  110. jsonData = JSON.parse(xhr.responseText);
  111. callback(jsonData, paramStr);
  112. } else {
  113. jsonData = JSON.parse('{"message":"后台请求错误(status:' + status + ')"}');
  114. console.log(xhr.responseText)
  115. error(jsonData, paramStr);
  116. }
  117. }
  118. };
  119. // 添加header
  120. if(headers) {
  121. for (var key in headers) {
  122. xhr.setRequestHeader(key,headers[key]);
  123. }
  124. }
  125. if(method == GET_TYPE) {
  126. var queryString = [];
  127. for (var key in params) {
  128. var p = key + '=' + encodeURIComponent(params[key]);
  129. queryString.push(p);
  130. }
  131. url = url + '?' + queryString.join('&');
  132. xhr.open(method, url, true);
  133. xhr.send();
  134. } else if(method == POST_TYPE) {
  135. xhr.open(method, url, true);
  136. if(form) {
  137. var formData = new FormData(form);
  138. // 添加json
  139. formData.append(UPLOAD_FORM_DATA_NAME, paramStr);
  140. xhr.send(formData);
  141. } else {
  142. xhr.setRequestHeader(CONTENT_TYPE_KEY, CONTENT_TYPE_JSON);
  143. xhr.send(paramStr);
  144. }
  145. } else {
  146. throw new Error('不支持的method:' + method);
  147. }
  148. }
  149. /**
  150. * 创建XHR对象
  151. * @private
  152. */
  153. ,createXhrObject:function() {
  154. var methods = [
  155. function(){ return new XMLHttpRequest();}
  156. ,function(){ return new ActiveXObject('Msxml2.XMLHTTP');}
  157. ,function(){ return new ActiveXObject('Microsoft.XMLHTTP');}
  158. ];
  159. var xhr = null;
  160. for(var i=0,len=methods.length; i<len; i++) {
  161. try {
  162. xhr = methods[i]();
  163. } catch (e) {
  164. continue;
  165. }
  166. this.createXhrObject = methods[i];
  167. return xhr;
  168. }
  169. throw new Error("创建XHR对象失败");
  170. }
  171. }
  172. /**
  173. * 请求
  174. * @param opts.name 接口名
  175. * @param opts.version 版本号
  176. * @param opts.method 请求方式
  177. * @param opts.data 请求数据,json对象
  178. * @param opts.access_token
  179. * @param opts.form 表单dom
  180. * @param opts.callback 响应回调
  181. * @param opts.jwt jwt
  182. */
  183. function request(opts) {
  184. var name = opts.name,
  185. version = opts.version || config.default_version,
  186. data = opts.data || {},
  187. callback = opts.callback,
  188. accessToken = opts.access_token,
  189. url = opts.url || config.url;
  190. var headers = {};
  191. var postData = {};
  192. postData[config.api_name] = name;
  193. postData[config.version_name] = version;
  194. postData[config.app_key_name] = config.app_key;
  195. postData[config.data_name] = encodeURIComponent(JSON.stringify(data));
  196. postData[config.timestamp_name] = formatDate(new Date());
  197. postData[config.format_name] = DEFAULT_FORMAT;
  198. if(accessToken) {
  199. postData[config.access_token_name] = accessToken;
  200. }
  201. postData[config.sign_name] = buildSign(postData,config.secret);
  202. var jwt = opts.jwt || config.jwt; // 优先使用opts中的jwt
  203. if(jwt) {
  204. headers['Authorization'] = 'Bearer ' + jwt;
  205. }
  206. ajax.request({
  207. url:url
  208. ,method:opts.method
  209. ,params:postData
  210. ,headers:headers
  211. ,form:opts.form
  212. ,callback:callback
  213. ,error:opts.error
  214. });
  215. }
  216. var sdk = {
  217. config:function(cfg) {
  218. copy(cfg,config);
  219. }
  220. /**
  221. * post请求
  222. * @param opts.name 接口名
  223. * @param opts.version 版本号
  224. * @param opts.data 请求数据,json对象
  225. * @param opts.access_token
  226. * @param opts.form 表单dom
  227. * @param opts.callback 响应回调
  228. * @param opts.jwt jwt
  229. */
  230. ,post:function(opts) {
  231. opts.method = POST_TYPE;
  232. request(opts);
  233. }
  234. /**
  235. * get请求
  236. * @param opts.name 接口名
  237. * @param opts.version 版本号
  238. * @param opts.data 请求数据,json对象
  239. * @param opts.access_token
  240. * @param opts.callback 响应回调
  241. * @param opts.jwt jwt
  242. */
  243. ,get:function(opts) {
  244. if(opts.form) {
  245. throw new Error('get方式不支持上传功能');
  246. }
  247. opts.method = GET_TYPE;
  248. request(opts);
  249. }
  250. }
  251. window.sdk = sdk;
  252. })();