java 調用企查查API查詢企業信息

效果圖:

首先需要設置token,API中要求token的格式爲key+Timespan+SecretKey組成的32位md5加密的大寫字符串,所以我也附贈了MD5加密的工具類。token要放在http的header 頭中,所以我在get請求的工具類中增加了一個header。

    //添加header 頭
                httpGet.setHeader("Token",token);
                httpGet.setHeader("Timespan",timeSpan);

權限驗證所提到的key,SecretKey均可在“我的接口”中查詢到

下面附上代碼。

HttpClientUtil :HTTP請求的工具類。裏面封裝好了,get、post 有無參數的請求情況。

    package dlighttop.apitest.apitest;
     
    import java.io.IOException;
    import java.net.URI;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
     
    import org.apache.http.Header;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.client.utils.URIBuilder;
    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.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
     
    public class HttpClientUtil {
     
        /**
         * 帶參數的get請求
         * @param url
         * @param param
         * @return String
         */
        public static String doGet(String url, Map<String, String> param) {
            // 創建Httpclient對象
            CloseableHttpClient httpclient = HttpClients.createDefault();
     
            String resultString = "";
            CloseableHttpResponse response = null;
            try {
                // 創建uri
                URIBuilder builder = new URIBuilder(url);
     
                if (param != null) {
                    for (String key : param.keySet()) {
                        builder.addParameter(key, param.get(key));
                    }
                }
                URI uri = builder.build();
                // 創建http GET請求
                HttpGet httpGet = new HttpGet(uri);
                // 執行請求
                response = httpclient.execute(httpGet);
                // 判斷返回狀態是否爲200
                if (response.getStatusLine().getStatusCode() == 200) {
                    resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (response != null) {
                        response.close();
                    }
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return resultString;
        }
     
     
        /**
         * 帶參數的get請求
         * @param url
         * @param param
         * @return String
         */
        public static String doGet(String url,String token,String timeSpan,Object o) {
            // 創建Httpclient對象
            CloseableHttpClient httpclient = HttpClients.createDefault();
     
            String resultString = "";
            CloseableHttpResponse response = null;
            try {
                // 創建uri
                URIBuilder builder = new URIBuilder(url);
     
     
                URI uri = builder.build();
                // 創建http GET請求
                HttpGet httpGet = new HttpGet(uri);
                //添加header 頭
                httpGet.setHeader("Token",token);
                httpGet.setHeader("Timespan",timeSpan);
                // 執行請求
                response = httpclient.execute(httpGet);
                // 判斷返回狀態是否爲200
                if (response.getStatusLine().getStatusCode() == 200) {
                    resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (response != null) {
                        response.close();
                    }
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return resultString;
        }
     
     
    //
    //    /**
    //     * 不帶參數的get請求
    //     * @param url
    //     * @return String
    //     */
    //    public static String doGet(String url) {
    //        return doGet(url, null);
    //    }
     
        /**
         * 不帶參數的get請求
         *
         * @param s
         * @param url
         * @return String
         */
        public static String doGet(String url, String token, String timeSpan) {
            return doGet(url, token,timeSpan,null);
        }
     
        /**
         * 帶參數的post請求
         * @param url
         * @param param
         * @return String
         */
        public static String doPost(String url, Map<String, String> param) {
            // 創建Httpclient對象
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            String resultString = "";
            try {
                // 創建Http Post請求
                HttpPost httpPost = new HttpPost(url);
                // 創建參數列表
                if (param != null) {
                    List<NameValuePair> paramList = new ArrayList<>();
                    for (String key : param.keySet()) {
                        paramList.add(new BasicNameValuePair(key, param.get(key)));
                    }
                    // 模擬表單
                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                    httpPost.setEntity(entity);
                }
                // 執行http請求
                response = httpClient.execute(httpPost);
                resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return resultString;
        }
     
        /**
         * 不帶參數的post請求
         * @param url
         * @return String
         */
        public static String doPost(String url) {
            return doPost(url, null);
        }
     
        /**
         * 傳送json類型的post請求
         * @param url
         * @param json
         * @return String
         */
        public static String doPostJson(String url, String json) {
            // 創建Httpclient對象
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            String resultString = "";
            try {
                // 創建Http Post請求
                HttpPost httpPost = new HttpPost(url);
                // 創建請求內容
                StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
                httpPost.setEntity(entity);
                // 執行http請求
                response = httpClient.execute(httpPost);
                resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return resultString;
        }
    }

MD5Util:MD5加密的工具類。網上找的。生成32位大寫MD5碼

    package dlighttop.apitest.apitest;
     
    import java.security.MessageDigest;
     
    /**
     * <p>
     * Description:
     * </p>
     * <p>
     * Copyright: Copyright (c)2015
     * </p>
     * <p>
     * Company: tope
     * </p>
     * <P>
     * Created Date :2015-7-27
     * </P>
     *
     * @author zhangfeng
     * @version 1.0
     */
    public class MD5Util {
     
        public final static String MD5(String s) {
     
            char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
            try {
                byte[] btInput = s.getBytes();
                // 獲得MD5摘要算法的 MessageDigest 對象
                MessageDigest mdInst = MessageDigest.getInstance("MD5");
                // 使用指定的字節更新摘要
                mdInst.update(btInput);
                // 獲得密文
                byte[] md = mdInst.digest();
                // 把密文轉換成十六進制的字符串形式
                int j = md.length;
                char str[] = new char[j * 2];
                int k = 0;
                for (int i = 0; i < j; i++) {
                    byte byte0 = md[i];
                    str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                    str[k++] = hexDigits[byte0 & 0xf];
                }
                return new String(str);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
     
        public static void main(String[] args) {
            System.out.println(MD5("123456").toUpperCase());
        }
    }

程序的入口,這裏因爲時間比較緊,所以寫的比較亂。。。

    package dlighttop.apitest.apitest;
     
    import dlighttop.core.utils.MD5Util;
    import java.util.Date;
     
    public class identityCheck {
        public static boolean identityCheck(String token,String timeStamp){
            System.out.println("-----------------開始調用--------------->");
            System.out.println("token"+token);
            String key = "263d5d33**b54b2da7d7a2742fc17828";
            String keyword = "阿里巴巴";
            //企業關鍵字模糊查詢
            String url = "http://api.qichacha.com/ECIV4/Search?key=" + key + "&dtype=json" + "&keyword=" + keyword;
            //企業關鍵字獲取詳細信息
    //        String url = "http://api.qichacha.com/ECIV4/GetBasicDetailsByName?key=" + key + "&dtype=json" + "&keyword=" + keyword;
            System.out.println("請求url:" + url);
            boolean match = false; //是否匹配
            try {
                String result = HttpClientUtil.doGet(url,token,timeStamp);
                System.out.println("請求結果:" + result);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("<-----------------調用結束---------------");
            return match;
        }
     
        public static void main(String[] args) throws Exception{
            String key = "263d5d338cb54b2d**d7a2742fc17828";
            int secondTimestamp = getSecondTimestamp(new Date()); //精確到秒的時間戳
            String secretKey ="B24B271A56A3**F16B6B73FFF64D80B2"; //密鑰
            String token = MD5Util.MD5(key+secondTimestamp+secretKey); //token:驗證加密值(key+Timespan+SecretKey組成的32位md5加密的大寫字符串)
            System.out.println(token);
            identityCheck(token,secondTimestamp+"");
        }
     
        /**
         * 獲取精確到秒的時間戳
         * @return
         */
        public static int getSecondTimestamp(Date date){
            if (null == date) {
                return 0;
            }
            String timestamp = String.valueOf(date.getTime());
            int length = timestamp.length();
            if (length > 3) {
                return Integer.valueOf(timestamp.substring(0,length-3));
            } else {
                return 0;
            }
        }
    }

最後打個寫好的包,記錄一下,方便自己也方便大家。嘿嘿~
————————————————
版權聲明:本文爲CSDN博主「小楊丿」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_39425958/article/details/97401110

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章