全部产品

发送请求示例代码

更新时间:2017-06-07 13:26:11   分享:   

具体原理,参考数加API使用文档

  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.io.InputStreamReader;
  5. import java.io.PrintWriter;
  6. import java.net.HttpURLConnection;
  7. import java.net.URL;
  8. import java.net.URLConnection;
  9. import java.security.MessageDigest;
  10. import java.text.SimpleDateFormat;
  11. import java.util.Date;
  12. import java.util.Locale;
  13. import javax.crypto.spec.SecretKeySpec;
  14. import sun.misc.BASE64Encoder;
  15. import javax.crypto.Mac;
  16. public class Sender {
  17. /*
  18. * 计算MD5+BASE64
  19. */
  20. public static String MD5Base64(String s) {
  21. if (s == null)
  22. return null;
  23. String encodeStr = "";
  24. byte[] utfBytes = s.getBytes();
  25. MessageDigest mdTemp;
  26. try {
  27. mdTemp = MessageDigest.getInstance("MD5");
  28. mdTemp.update(utfBytes);
  29. byte[] md5Bytes = mdTemp.digest();
  30. BASE64Encoder b64Encoder = new BASE64Encoder();
  31. encodeStr = b64Encoder.encode(md5Bytes);
  32. } catch (Exception e) {
  33. throw new Error("Failed to generate MD5 : " + e.getMessage());
  34. }
  35. return encodeStr;
  36. }
  37. /*
  38. * 计算 HMAC-SHA1
  39. */
  40. public static String HMACSha1(String data, String key) {
  41. String result;
  42. try {
  43. // System.out.println("data: " + data);
  44. // System.out.println("key: " + key);
  45. SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
  46. Mac mac = Mac.getInstance("HmacSHA1");
  47. mac.init(signingKey);
  48. byte[] rawHmac = mac.doFinal(data.getBytes());
  49. result = (new BASE64Encoder()).encode(rawHmac);
  50. } catch (Exception e) {
  51. throw new Error("Failed to generate HMAC : " + e.getMessage());
  52. }
  53. return result;
  54. }
  55. /*
  56. * 等同于javaScript中的 new Date().toUTCString();
  57. */
  58. public static String toGMTString(Date date) {
  59. SimpleDateFormat df = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z", Locale.UK);
  60. df.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));
  61. return df.format(date);
  62. }
  63. /*
  64. * 发送POST请求
  65. */
  66. public static String sendPost(String url, String body, String ak_id, String ak_secret) {
  67. PrintWriter out = null;
  68. BufferedReader in = null;
  69. String result = "";
  70. try {
  71. URL realUrl = new URL(url);
  72. /*
  73. * http header 参数
  74. */
  75. String method = "POST";
  76. String accept = "json";
  77. String content_type = "application/json";
  78. String path = realUrl.getFile();
  79. String date = toGMTString(new Date());
  80. // 1.对body做MD5+BASE64加密
  81. String bodyMd5 = MD5Base64(body);
  82. String stringToSign = method + "\n" + accept + "\n" + bodyMd5 + "\n" + content_type + "\n" + date + "\n"
  83. + path;
  84. // 2.计算 HMAC-SHA1
  85. String signature = HMACSha1(stringToSign, ak_secret);
  86. // 3.得到 authorization header
  87. String authHeader = "Dataplus " + ak_id + ":" + signature;
  88. // 打开和URL之间的连接
  89. URLConnection conn = realUrl.openConnection();
  90. // 设置通用的请求属性
  91. conn.setRequestProperty("accept", accept);
  92. conn.setRequestProperty("content-type", content_type);
  93. conn.setRequestProperty("date", date);
  94. conn.setRequestProperty("Authorization", authHeader);
  95. conn.setRequestProperty("Accept-Charset", "UTF-8");
  96. // 发送POST请求必须设置如下两行
  97. conn.setDoOutput(true);
  98. conn.setDoInput(true);
  99. // 获取URLConnection对象对应的输出流
  100. out = new PrintWriter(conn.getOutputStream());
  101. // 发送请求参数
  102. out.print(body);
  103. // flush输出流的缓冲
  104. out.flush();
  105. // 定义BufferedReader输入流来读取URL的响应
  106. InputStream is;
  107. HttpURLConnection httpconn = (HttpURLConnection) conn;
  108. if (httpconn.getResponseCode() == 200) {
  109. is = httpconn.getInputStream();
  110. } else {
  111. is = httpconn.getErrorStream();
  112. }
  113. InputStreamReader sr = new InputStreamReader(is,"utf-8");
  114. in = new BufferedReader(sr);
  115. String line;
  116. while ((line = in.readLine()) != null) {
  117. result += line;
  118. }
  119. } catch (Exception e) {
  120. System.out.println("发送 POST 请求出现异常!" + e);
  121. e.printStackTrace();
  122. }
  123. // 使用finally块来关闭输出流、输入流
  124. finally {
  125. try {
  126. if (out != null) {
  127. out.close();
  128. }
  129. if (in != null) {
  130. in.close();
  131. }
  132. } catch (IOException ex) {
  133. ex.printStackTrace();
  134. }
  135. }
  136. return result;
  137. }
  138. }
本文导读目录
本文导读目录
以上内容是否对您有帮助?