package com.fs.erp.utils;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.security.MessageDigest;

public class CommonUtils {
    public static String sign(String data, String secret) {
        StringBuilder enValue = new StringBuilder();
        enValue.append(secret);
        enValue.append(data.toString());
        enValue.append(secret);
        return encryptByMD5(enValue.toString());
    }
    private static String encryptByMD5(String data) {
        StringBuilder   sign = new StringBuilder();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[]   bytes = md.digest(data.getBytes("UTF-8"));
            for   (int i = 0; i < bytes.length; i++) {
                String   hex = Integer.toHexString(bytes[i] & 0xFF);
                if   (hex.length() == 1) {
                    sign.append("0");
                }
                sign.append(hex.toUpperCase());
            }

        }catch (Exception e) {
            e.printStackTrace();
        }
        return   sign.toString();
    }
    public static String sendPost(String url, String data) {
        try {
            CloseableHttpClient httpclient = null;
            CloseableHttpResponse httpresponse = null;
            try   {
                httpclient   = HttpClients.createDefault();

                HttpPost httppost = new HttpPost(url);

                StringEntity stringentity = new StringEntity(
                        data,
                        ContentType.create("text/json",   "UTF-8"));
                httppost.setEntity(stringentity);
                httpresponse   = httpclient.execute(httppost);
                String   response = EntityUtils
                        .toString(httpresponse.getEntity());
                return response;
            }   finally {

                if   (httpclient != null) {

                    httpclient.close();

                }

                if   (httpresponse != null) {

                    httpresponse.close();

                }

            }

        }   catch (Exception e) {

            e.printStackTrace();

        }
        return null;
    }
}
