调用接口, Test.java(不用任何包, MD5大写32位加密,HttpURLConnection)

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;

public class Test {

  public static void main(String[] args) throws Exception {
    String cpOrderId = String.valueOf(System.currentTimeMillis());
    String cpId = "1143";
    String goodsCode = "8782842469";
    int orderType = 0;
    String mobile = "18370017024";
    String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
    int sourceType = 2;
    int channelCode = 1;
    String scope = "test";
    String sign = md5("channelCode=1&cpId=1143&cpOrderId=" + cpOrderId
      + "&goodsCode=8782842469&mobile=18370017024&orderType=0&sourceType=2&timestamp=" + timestamp
      + "&key=be54c40e601cea5c74414382218ff81d");

    StringBuilder body = new StringBuilder().append("{").append("\"cpOrderId\":\"" + cpOrderId + "\",")
      .append("\"cpId\":\"" + cpId + "\",").append("\"goodsCode\":\"" + goodsCode + "\",")
      .append("\"orderType\":" + orderType + ",").append("\"mobile\":\"" + mobile + "\",")
.      append("\"timestamp\":\"" + timestamp + "\",").append("\"sourceType\":\"" + sourceType + "\",")
      .append("\"channelCode\":\"" + channelCode + "\",").append("\"scope\":\"" + scope + "\",")
      .append("\"sign\":\"" + sign + "\"").append("}");

    String result = post("http://220.194.53.168:7020/api/b2b/sendVerificationCode",
      "data=" + URLEncoder.encode(body.toString(), "UTF-8"), "application/x-www-form-urlencoded");
    System.out.println(result);
  }

  public static String md5(String s) throws Exception {
    MessageDigest md = MessageDigest.getInstance("MD5");
    byte[] bytes = md.digest(s.getBytes("UTF-8"));
    final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
    StringBuilder ret = new StringBuilder(bytes.length * 2);
    for (int i = 0; i < bytes.length; i++) {
      ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
      ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
    }
    return ret.toString();
  }

  public static String post(String url, String body, String contentType) throws Exception {
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", contentType);
    conn.setDoOutput(true);
    OutputStream out = conn.getOutputStream();
    out.write(body.getBytes("UTF-8"));
    out.flush();
    BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
    byte[] bs = new byte[10240];
    int count;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    while (-1 != (count = in.read(bs))) {
      baos.write(bs, 0, count);
    }
    return new String(baos.toByteArray());
  }

}

posted @ 2018-04-02 21:34  流去  阅读(226)  评论(0编辑  收藏  举报