import java.io.*;
import java.math.BigInteger;
import java.net.*;
import java.nio.Buffer;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) throws IOException, NoSuchAlgorithmException {

        // TODO 请自行进行异常处理和关闭资源
        String companyId = "your_company_id";
        String key = "your_key";
        Map<String, String> parameters = new HashMap<>();
        parameters.put("data", "['728350000001']");
        parameters.put("company_id", companyId);
        parameters.put("msg_type", "NEW_TRACES");

        String strToDigest = paramsToQueryString(parameters) + key;
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(strToDigest.getBytes(Charset.forName("UTF-8")));

        String dataDigest = Base64.getEncoder().encodeToString(md.digest());
        URL url = new URL("http://japi.zto.cn/traceInterfaceNewTraces");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        con.setDoOutput(true);
        con.setConnectTimeout(5000);
        con.setReadTimeout(5000);
        con.setRequestProperty("x-datadigest", dataDigest);
        con.setRequestProperty("x-companyid", companyId);
        DataOutputStream out = new DataOutputStream(con.getOutputStream());
        out.write(paramsToQueryStringUrlencoded(parameters).getBytes(Charset.forName("UTF-8")));
        out.flush();
        out.close();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer content = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine);
        }
        in.close();

        System.out.println(content.toString());

    }

    public static String paramsToQueryString(Map<String, String> params) {
        return params.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).collect(Collectors.joining("&"));
    }


    public static String paramsToQueryStringUrlencoded(Map<String, String> params) {
        return params.entrySet().stream().map(e -> {
            try {
                return e.getKey() + "=" + URLEncoder.encode(e.getValue(), "UTF-8");
            } catch (UnsupportedEncodingException e1) {
                return e.getValue();
            }
        }).collect(Collectors.joining("&"));
    }
}

results matching ""

    No results matching ""