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;
        }
    }
}

最后打个写好的包,记录一下,方便自己也方便大家。嘿嘿~

评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值