具体原理,参考
数加API使用文档<pre style='background: rgb(246, 246, 246); font: 12px/1.6 "YaHei Consolas Hybrid", Consolas, "Meiryo UI", "Malgun Gothic", "Segoe UI", "Trebuchet MS", Helvetica, monospace, monospace; padding: 10px; outline: 0px; border-radius: 3px; border: 1px solid rgb(221, 221, 221); color: rgb(51, 51, 51); text-transform: none; text-indent: 0px; letter-spacing: normal; overflow: auto; margin-top: 0px; margin-right: 0px; margin-bottom: 0px !important; margin-left: 0px; word-spacing: 0px; white-space: pre-wrap; word-wrap: break-word; box-sizing: border-box; orphans: 2; widows: 2; font-size-adjust: none; font-stretch: normal; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;' prettyprinted?="" linenums="">
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.net.URLConnection;
- import java.security.MessageDigest;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import java.util.Locale;
- import javax.crypto.spec.SecretKeySpec;
- import sun.misc.BASE64Encoder;
- import javax.crypto.Mac;
- public class Sender {
- /*
- * 计算MD5+BASE64
- */
- public static String MD5Base64(String s) {
- if (s == null)
- return null;
- String encodeStr = "";
- byte[] utfBytes = s.getBytes();
- MessageDigest mdTemp;
- try {
- mdTemp = MessageDigest.getInstance("MD5");
- mdTemp.update(utfBytes);
- byte[] md5Bytes = mdTemp.digest();
- BASE64Encoder b64Encoder = new BASE64Encoder();
- encodeStr = b64Encoder.encode(md5Bytes);
- } catch (Exception e) {
- throw new Error("Failed to generate MD5 : " + e.getMessage());
- }
- return encodeStr;
- }
- /*
- * 计算 HMAC-SHA1
- */
- public static String HMACSha1(String data, String key) {
- String result;
- try {
- // System.out.println("data: " + data);
- // System.out.println("key: " + key);
- SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
- Mac mac = Mac.getInstance("HmacSHA1");
- mac.init(signingKey);
- byte[] rawHmac = mac.doFinal(data.getBytes());
- result = (new BASE64Encoder()).encode(rawHmac);
- } catch (Exception e) {
- throw new Error("Failed to generate HMAC : " + e.getMessage());
- }
- return result;
- }
- /*
- * 等同于javaScript中的 new Date().toUTCString();
- */
- public static String toGMTString(Date date) {
- SimpleDateFormat df = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z", Locale.UK);
- df.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));
- return df.format(date);
- }
- /*
- * 发送POST请求
- */
- public static String sendPost(String url, String body, String ak_id, String ak_secret) {
- PrintWriter out = null;
- BufferedReader in = null;
- String result = "";
- try {
- URL realUrl = new URL(url);
- /*
- * http header 参数
- */
- String method = "POST";
- String accept = "json";
- String content_type = "application/json";
- String path = realUrl.getFile();
- String date = toGMTString(new Date());
- // 1.对body做MD5+BASE64加密
- String bodyMd5 = MD5Base64(body);
- String stringToSign = method + "\n" + accept + "\n" + bodyMd5 + "\n" + content_type + "\n" + date + "\n"
- + path;
- // 2.计算 HMAC-SHA1
- String signature = HMACSha1(stringToSign, ak_secret);
- // 3.得到 authorization header
- String authHeader = "Dataplus " + ak_id + ":" + signature;
- // 打开和URL之间的连接
- URLConnection conn = realUrl.openConnection();
- // 设置通用的请求属性
- conn.setRequestProperty("accept", accept);
- conn.setRequestProperty("content-type", content_type);
- conn.setRequestProperty("date", date);
- conn.setRequestProperty("Authorization", authHeader);
- conn.setRequestProperty("Accept-Charset", "UTF-8");
- // 发送POST请求必须设置如下两行
- conn.setDoOutput(true);
- conn.setDoInput(true);
- // 获取URLConnection对象对应的输出流
- out = new PrintWriter(conn.getOutputStream());
- // 发送请求参数
- out.print(body);
- // flush输出流的缓冲
- out.flush();
- // 定义BufferedReader输入流来读取URL的响应
- InputStream is;
- HttpURLConnection httpconn = (HttpURLConnection) conn;
- if (httpconn.getResponseCode() == 200) {
- is = httpconn.getInputStream();
- } else {
- is = httpconn.getErrorStream();
- }
- InputStreamReader sr = new InputStreamReader(is,"utf-8");
- in = new BufferedReader(sr);
- String line;
- while ((line = in.readLine()) != null) {
- result += line;
- }
- } catch (Exception e) {
- System.out.println("发送 POST 请求出现异常!" + e);
- e.printStackTrace();
- }
- // 使用finally块来关闭输出流、输入流
- finally {
- try {
- if (out != null) {
- out.close();
- }
- if (in != null) {
- in.close();
- }
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- }
- return result;
- }
- }