BihuHttpUtil.java Source code

Java tutorial

Introduction

Here is the source code for BihuHttpUtil.java

Source

import java.io.BufferedReader;
import java.io.DataOutputStream;
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.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * Created by fengwen on 2016/6/6.
 */
public class BihuHttpUtil {
    /**
     * ?URL??GET
     *
     * @param url
     *            ??URL
     * @param param
     *            ?? name1=value1&name2=value2 ?
     * @return URL ??
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // URL
            URLConnection connection = realUrl.openConnection();
            // 
            connection.setRequestProperty("Host", "quote.zhonghe-bj.com:8085");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
            connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
            // 
            connection.connect();
            //  BufferedReader???URL?
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("??GET?" + e);
            e.printStackTrace();
        }
        // finally???
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * ? URL ??POST
     *
     * @param url
     *            ?? URL
     * @param param
     *            ?? name1=value1&name2=value2 ?
     * @return ??
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // URL
            URLConnection conn = realUrl.openConnection();
            // 
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // ??POST
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // ?URLConnection?
            out = new PrintWriter(conn.getOutputStream());
            // ???
            out.print(param);
            // flush?
            out.flush();
            // BufferedReader???URL?
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            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;
    }

    public static String doHttpPost(String xmlInfo, String URL) {
        System.out.println("??:" + xmlInfo);
        byte[] xmlData = xmlInfo.getBytes();
        InputStream instr = null;
        java.io.ByteArrayOutputStream out = null;
        try {
            URL url = new URL(URL);
            URLConnection urlCon = url.openConnection();
            urlCon.setDoOutput(true);
            urlCon.setDoInput(true);
            urlCon.setUseCaches(false);
            urlCon.setRequestProperty("Content-Type", "text/xml");
            urlCon.setRequestProperty("Content-length", String.valueOf(xmlData.length));
            System.out.println(String.valueOf(xmlData.length));
            DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
            printout.write(xmlData);
            printout.flush();
            printout.close();
            instr = urlCon.getInputStream();
            byte[] bis = IOUtils.toByteArray(instr);
            String ResponseString = new String(bis, "UTF-8");
            if ((ResponseString == null) || ("".equals(ResponseString.trim()))) {
                System.out.println("");
            }
            System.out.println("?:" + ResponseString);
            return ResponseString;

        } catch (Exception e) {
            e.printStackTrace();
            return "0";
        } finally {
            try {
                out.close();
                instr.close();
            } catch (Exception ex) {
                return "0";
            }
        }
    }

    /**
     * ? URL ??POST
     *
     * @param url
     *               ?? URL
     * @param param
     *               ?? name1=value1&name2=value2 ?
     * @param sessionId
     *             ???
     * @return ??
     */
    public static Map<String, String> sendPost(String url, String param, String sessionId) {
        Map<String, String> resultMap = new HashMap<String, String>();
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // URL
            URLConnection conn = realUrl.openConnection();
            // 
            //conn.setRequestProperty("Host", "quote.zhonghe-bj.com:8085");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            conn.setRequestProperty("Accept", "*/*");
            conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
            conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
            if (StringUtils.isNotBlank(sessionId)) {
                conn.setRequestProperty("Cookie", sessionId);
            }
            // ??POST
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // ?URLConnection?
            out = new PrintWriter(conn.getOutputStream());
            // ???
            out.print(param);
            // flush?
            out.flush();
            // BufferedReader???URL?
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String cookieValue = conn.getHeaderField("Set-Cookie");
            resultMap.put("cookieValue", cookieValue);
            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();
            }
        }
        resultMap.put("result", result);
        return resultMap;
    }

    /**
     * ??HTTPJSON?
     * @param url
     * @param jsonStr
     */
    public static String sendPostForJson(String url, String jsonStr) {
        StringBuffer sb = new StringBuffer("");
        try {
            //
            URL realUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            connection.connect();
            //POST
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(jsonStr.getBytes("UTF-8"));//???
            out.flush();
            out.close();
            //??
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String lines;
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                sb.append(lines);
            }
            reader.close();
            // 
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        String key = "csdfse784";
        String agent = "3820";
        //      String carNO = "HD3639";
        //      String EngineNo = "1026510";
        //      String CarVin = "LHGRU5746F2026462";
        //      String RegisterDate = "2015-04-03";
        //      String MoldName = "HG7180HAM5";
        //      String IntentionCompany = "0";

        //      String carNO = "N3HU88";
        //      String EngineNo = "8634342";
        //      String CarVin = "LDCC13L25A0206503";
        //      String RegisterDate = "2010-04-28";
        //      String MoldName = "?DC7165DTA";
        //      String IntentionCompany = "2";

        //String carNO = "P55M11";
        String EngineNo = "4LA4D8297";
        String CarVin = "LGXC16DF4A0169664";
        String RegisterDate = "2006-10-01";
        String MoldName = "F3";
        String IntentionCompany = "1";
        //"ForceTotal":627.56,"TaxTotal":400

        //String carNO = "PT3G98";
        //String carNO = "N3HU88";
        //String carNO = "A723KG";
        //String carNO = "QA5M75";
        //String carNO = "KT3495";
        //String carNO = "KV5909";
        //String carNO = "QWZ015";
        //String carNO = "Q8D075";
        //String carNO = "KV5909";
        //String carNO="F03E65";
        //String carNO="P55M11";
        //String carNO="A723KG";
        //String carNO="QA5M75";
        //String carNO="?JC1112";
        //String carNO="QWZ015";
        //String carNO = "MH0501";
        //String carNO = "P2QZ85";
        //String carNO = "NQA575";
        //String carNO = "Q2PE81";
        //String carNO = "LQ1190";
        //String carNO = "HGD056";
        //String carNO = "MM3767";
        String carNO = "F20403";

        String custKey = "e8370f8fb7d7d6ec7bcaa8b3b738e409";

        String param1 = "LicenseNo=" + carNO + "&CityCode=1&Agent=" + agent + "&IsPublic=0&CustKey=" + custKey;
        //String paramTest = "LicenseNo=P55M11&CityCode=1&Agent=3820&IsPublic=0&CustKey=492f4a6c11781385e9cf08651e77e148&SecCode=6634bf16b66dddd263a824f79f9a7e3a";
        String secCode1 = MD5(param1 + key);
        param1 = param1 + "&SecCode=" + secCode1.toLowerCase();
        String url1 = "http://it.91bihu.com/api/CarInsurance/getreinfo";
        String result = sendGet(url1, param1);
        System.err.println(result);
        System.err.println("" + String.valueOf(System.currentTimeMillis() - start));

        //
        //      String url = "http://i.91bihu.com/api/CarInsurance/PostPrecisePrice";
        //      //?JSON?
        //      Map<String, String> jsonObj = new HashMap<>();
        //      //?
        //      jsonObj.put("IsSingleSubmit", "1");//IsSingleSubmit      Int   ?????1=0=?
        //      jsonObj.put("IntentionCompany", IntentionCompany);//IntentionCompany      String   ????(-1:????0:?1:?2:?)
        //      //?
        //      jsonObj.put("LicenseNo", carNO);//LicenseNo      String   ?
        //      jsonObj.put("EngineNo", EngineNo);//EngineNo      String   ??
        //      jsonObj.put("CarVin", CarVin);//CarVin      String   ?
        //      jsonObj.put("RegisterDate", RegisterDate);//RegisterDate      string   
        //      jsonObj.put("MoldName", MoldName);//MoldName      String   ??
        //      jsonObj.put("CarType", "0");//CarType      Int   01
        //      jsonObj.put("IsNewCar", "0");//IsNewCar      Int   ?0?1
        //      jsonObj.put("CarUsedType", "0");//CarUsedType      string   0??????
        //      jsonObj.put("Citycode", "10");//Citycode      Int   Id???:110000
        //      //??
        //      jsonObj.put("ForceTax", "1");//ForceTax      Int   +(1:0?)
        //      jsonObj.put("BoLi", "1");//BoLi      Double   ?0-??12?
        //      jsonObj.put("CheDeng", "0");//CheDeng      Double   ??????0-??1-2-?
        //      jsonObj.put("SheShui", "1");//SheShui      Double   ?0-??1?
        //      jsonObj.put("HuaHen", "2000");//HuaHen      Double   ?0-??>0?(?)200050001000020000
        //      jsonObj.put("SiJi", "10000");//SiJi      Double   (?) 0-??>0?(?1000020000300004000050000100000200000
        //      jsonObj.put("ChengKe", "10000");//ChengKe      Double   () 0-??>0?(?)1000020000300004000050000100000200000
        //      jsonObj.put("CheSun", "1");//CheSun      Double   ??0-??>0?
        //      jsonObj.put("DaoQiang", "1");//DaoQiang      Double   ?0-??>0?
        //      jsonObj.put("SanZhe", "50000");//SanZhe      Double   ?0-??>0?(?)5000010000015000020000030000050000010000001500000
        //      jsonObj.put("ZiRan", "1");//ZiRan      Double   ?0-??1?
        //      jsonObj.put("BuJiMianCheSun", "1");//BuJiMianCheSun      Double   ??(?) 0-??1?
        //      jsonObj.put("BuJiMianDaoQiang", "1");//BuJiMianDaoQiang      Double   ??() 0-??1?
        //      jsonObj.put("BuJiMianFuJia", "1");//BuJiMianFuJia      Double   ??() 0-??1?
        //      jsonObj.put("BuJiMianRenYuan", "1");//BuJiMianRenYuan      Double   ??() 0-??1?
        //      jsonObj.put("BuJiMianSanZhe", "1");//BuJiMianSanZhe      Double   ??() 0-??1?
        //??
        //
        //      jsonObj.put("CustKey", custKey);
        //      jsonObj.put("Agent", agent);//Agent      Int   ?
        //      StringBuffer paramSb = new StringBuffer();
        //      for(String mapKey : jsonObj.keySet()){
        //         String value = jsonObj.get(mapKey);
        //         paramSb.append(mapKey + "=" + value + "&");
        //      }
        //      String secCode = MD5(paramSb.toString() + key).toLowerCase();
        //      paramSb.append("secCode=" + secCode);

        //      String result2 = sendGet(url, paramSb.toString());
        //      System.err.println(result2);

        //??
        //      for(int i=0;i<40;i++){
        //         Thread.sleep(1000L);
        //         String param = "LicenseNo=" + carNO + "&IntentionCompany=" + IntentionCompany + "&Agent=" + agent + "&CustKey=" + custKey;
        //         String secCode2 = MD5(param + key);
        //         param = param + "&SecCode=" + secCode2.toLowerCase();
        //         String url2 = "http://i.91bihu.com/api/CarInsurance/GetPrecisePrice";
        //         String result1 = sendGet(url2, param);
        //         System.err.println(result1);
        //      }

        //      //???
        //      String param = "LicenseNo=" + carNO + "&IntentionCompany=" + IntentionCompany + "&Agent=" + agent;
        //      String secCode2 = MD5(param + key);
        //      param = param + "&SecCode=" + secCode2.toLowerCase();
        //      String url4 = "http://i.91bihu.com/api/CarInsurance/GetSubmitInfo";
        //      String result4 = sendGet(url4, param);
        //      System.err.println(result4);

        //??
        String param5 = "LicenseNo=" + carNO + "&Agent=" + agent + "&CustKey=" + custKey;
        String secCode5 = MD5(param5 + key);
        param5 = param5 + "&SecCode=" + secCode5.toLowerCase();
        String url5 = "http://i.91bihu.com/api/Claim/GetCreditInfo";
        String result5 = sendGet(url5, param5);
        System.err.println(result5);

        System.err.println("" + String.valueOf(System.currentTimeMillis() - start));
    }

    public static void main1(String[] args) throws Exception {

        String key = "csdfse784";
        //???
        //      String secCode = MD5("213520030193P55M111100003820" + key);
        //      System.err.println(secCode.toLowerCase());
        //      String url = "http://m.91bihu.com/api/CommonInsuranceBusiness/GetReInsuranceInfo";
        //      String param = "lastYearCompany=2&mobile=13520030193&useridentity=&carLicense=P55M11&citycode=110000&agent=3820&secCode=" + secCode.toLowerCase();
        //      String result = sendGet(url, param);
        //      System.err.println(result);

        //()
        //      Map<String, String> map = new HashMap<String,String>();
        //      map.put("registerDate", "2010-06-21");//
        //      map.put("moldName", "QCJ7150A6");//??
        //      map.put("engineNo", "4LA4D8297");//??
        //      map.put("carVin", "LGXC16DF4A0169664");//?
        //      map.put("carLicense", "P55M11");//?
        //      map.put("mobile", "13520030193");//?
        //      map.put("intentionCompany", "0");//????(-1:??0:?1:?2:?)
        //      map.put("userIdentity", "");//(?openidapp???)
        //      map.put("carType", "0");//?/0?1
        //      map.put("isNewCar", "0");//?0?1
        //      map.put("useType", "0");//??/???0???1??
        //      map.put("citycode", "110000");//Id???:110000
        //      map.put("boli", "0");//?0-??12?
        //      map.put("bujimianchesun", "0");//??(?) 0-??1?
        //      map.put("bujimiandaoqiang", "0");//??() 0-??1?
        //      map.put("bujimianfujia", "0");//??() 0-??1?
        //      map.put("bujimianrenyuan", "0");//??() 0-??1?
        //      map.put("bujimiansanzhe", "0");//??() 0-??1?
        //      map.put("chedeng", "0");//??????0-??1-2-?
        //      map.put("sheshui", "0");//?0-??1?
        //      map.put("huahen", "0");//?0-??>0?(?)200050001000020000
        //      map.put("siji", "10000.00");//(?) 0-??>0?(?1000020000300004000050000100000200000
        //      map.put("chengke", "10000");//() 0-??>0?(?)1000020000300004000050000100000200000
        //      map.put("chesun", "0");//??0-??>0?
        //      map.put("daoqiang", "0");//?0-??>0?
        //      map.put("sanzhe", "50000");//?0-??>0?(?)5000010000015000020000030000050000010000001500000
        //      map.put("ziran", "0");//?0-??1?
        //      map.put("agent", "4820");
        //      StringBuffer paramSb = new StringBuffer();
        //      for(String mapKey : map.keySet()){
        //         String value = map.get(mapKey);
        //         paramSb.append(mapKey + "=" + value + "&");
        //      }
        //      String secCode = MD5("013520030193P55M111100004820" + key);
        //      System.err.println(secCode);
        //      paramSb.append("secCode=" + secCode.toLowerCase());
        //      String url = "http://m.91bihu.com/api/CommonInsuranceBusiness/GetPrecisePrice";
        //      String result = sendGet(url, paramSb.toString());
        //      System.err.println(result);

        //      String key = "csdfse784";
        //      //?
        //      String url = "http://m.91bihu.com/api/CommonInsuranceBusiness/GetCreditInfoBy";
        //      String secCode = MD5("P55M113820" + key);
        //      String param = "LicenseNo=P55M11&agent=3820&secCode=" + secCode.toLowerCase();
        //      String result = sendGet(url, param);
        //      System.err.println(result);
        //      System.err.println("" + String.valueOf(System.currentTimeMillis() - start));
    }

    public final static String MD5(String pwd) {
        // 
        char md5String[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        try {
            // ? String ? byte? byte
            byte[] btInput = pwd.getBytes();

            // ???????
            MessageDigest mdInst = MessageDigest.getInstance("MD5");

            // MessageDigest update?? byte?
            mdInst.update(btInput);

            // ??digest
            byte[] md = mdInst.digest();

            // ?????
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) { // i = 0
                byte byte0 = md[i]; // 95
                str[k++] = md5String[byte0 >>> 4 & 0xf]; // 5
                str[k++] = md5String[byte0 & 0xf]; // F
            }

            // ??
            return new String(str);

        } catch (Exception e) {
            return null;
        }
    }
}