JAVA调用企查查相关接口

一.准备工作:

企查查开放平台

1、登录企查查开放平台注册账号:充值金额(500起充)或者进行企业认证,企业认证成后有20次免费测试的机会!

2、根据项目需求开通想要调用的接口

 二、撸代码

1、封装企查查工具类:

import java.io.IOException;
import java.util.regex.Pattern;

import org.apache.commons.codec.digest.DigestUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class QiChaChaUtil {
    // 获取返回码 Res Code
    public static class HttpCodeRegex {
        private static final String ABNORMAL_REGIX = "(101)|(102)";
        private static final Pattern pattern = Pattern.compile(ABNORMAL_REGIX);
        public static boolean isAbnornalRequest(final String status) {
            return pattern.matcher(status).matches();
        }
    }

    // 获取Auth Code
    public static final String[] RandomAuthentHeader(String appkey,String seckey) {
        String timeSpan = String.valueOf(System.currentTimeMillis() / 1000);
        String[] authentHeaders = new String[] { DigestUtils.md5Hex(appkey.concat(timeSpan).concat(seckey)).toUpperCase(), timeSpan };
        return authentHeaders;
    }

    // 解析JSON
    public static String FormartJson(String jsonString, String key) throws JSONException {
        JSONObject jObject = new JSONObject(jsonString);
        return (String) jObject.get(key);
    }

    // pretty print 返回值
    public static void PrettyPrintJson(String jsonString) throws JSONException {
        try {
            ObjectMapper mapper = new ObjectMapper();
            Object obj = mapper.readValue(jsonString, Object.class);
            String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
            System.out.println(indented);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2、http请求类

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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.methods.HttpUriRequest;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;


public class HttpHelper {

	// get 请求
	public static String httpGet(String url, Header[] headers) throws Exception {
		HttpUriRequest uriRequest = new HttpGet(url);
		if (null != headers)
			uriRequest.setHeaders(headers);
		CloseableHttpClient httpClient = null;
		try {
			httpClient = declareHttpClientSSL(url);
			CloseableHttpResponse httpresponse = httpClient.execute(uriRequest);
			HttpEntity httpEntity = httpresponse.getEntity();
			String result = EntityUtils.toString(httpEntity, REQ_ENCODEING_UTF8);
			return result;
		} catch (ClientProtocolException e) {
			System.out.println(String.format("http请求失败,uri{%s},exception{%s}", new Object[] { url, e }));
		} catch (IOException e) {
			System.out.println(String.format("IO Exception,uri{%s},exception{%s}", new Object[] { url, e }));
		} finally {
			if (null != httpClient)
				httpClient.close();
		}
		return null;
	}

	// post 请求
	public static String httpPost(String url, String params) throws Exception {
		HttpPost post = new HttpPost(url);
		post.addHeader("Content-Type", "application/json;charset=" + REQ_ENCODEING_UTF8);
		// 设置传输编码格式
		StringEntity stringEntity = new StringEntity(params, REQ_ENCODEING_UTF8);
		stringEntity.setContentEncoding(REQ_ENCODEING_UTF8);
		post.setEntity(stringEntity);
		HttpResponse httpresponse = null;
		CloseableHttpClient httpClient = null;
		try {
			httpClient = declareHttpClientSSL(url);
			httpresponse = httpClient.execute(post);
			HttpEntity httpEntity = httpresponse.getEntity();
			String result = EntityUtils.toString(httpEntity, REQ_ENCODEING_UTF8);
			return result;
		} catch (ClientProtocolException e) {
			System.out.println(String.format("http请求失败,uri{%s},exception{%s}", new Object[] { url, e }));
		} catch (IOException e) {
			System.out.println(String.format("IO Exception,uri{%s},exception{%s}", new Object[] { url, e }));
		} finally {
			if (null != httpClient)
				httpClient.close();
		}
		return null;
	}

	private static CloseableHttpClient declareHttpClientSSL(String url) {
		if (url.startsWith("https://")) {
			return sslClient();
		} else {
			return HttpClientBuilder.create().setConnectionManager(httpClientConnectionManager).build();
		}
	}

	/**
	 * 设置SSL请求处理
	 * 
	 */
	private static CloseableHttpClient sslClient() {
		try {
			SSLContext ctx = SSLContext.getInstance("TLS");
			X509TrustManager tm = new X509TrustManager() {
				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}

				public void checkClientTrusted(X509Certificate[] xcs, String str) {
				}

				public void checkServerTrusted(X509Certificate[] xcs, String str) {
				}
			};
			ctx.init(null, new TrustManager[] { tm }, null);
			SSLConnectionSocketFactory sslConnectionSocketFactory = SSLConnectionSocketFactory.getSocketFactory();
			return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		} catch (KeyManagementException e) {
			throw new RuntimeException(e);
		}
	}

	// this is config
	private static final String REQ_ENCODEING_UTF8 = "utf-8";
	private static PoolingHttpClientConnectionManager httpClientConnectionManager;

	public HttpHelper() {
		httpClientConnectionManager = new PoolingHttpClientConnectionManager();
		httpClientConnectionManager.setMaxTotal(100);
		httpClientConnectionManager.setDefaultMaxPerRoute(20);
	}

	// get 请求
	public static String httpGet(String url) throws Exception {
		return httpGet(url, null);
	}

3、yml文件配置对应参数

 

4、企业搜搜以及税号开票信息访问控制层代码

import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import jadp.base.ActionResult;
import jadp.zxks.qichacha.util.HttpHelper;
import jadp.zxks.qichacha.util.QiChaChaUtil;
import jadp.zxks.qichacha.vo.QccCompany;
import jadp.zxks.qichacha.vo.QccJsonResult;
import jadp.zxks.qichacha.vo.QccResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpHead;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;


@Slf4j
@RestController
@Api(tags = "qichacha", value = "qichacha")
@RequestMapping("/api/qichacha")
public class QiChaChaController {

    @Value("${qichacha.key}")
    private String key;
    @Value("${qichacha.secretKey}")
    private String secretKey;

    //企业搜索
    @GetMapping("/getList")
    public ActionResult<?> getList(@RequestParam("searchName") String searchName) {
        String reqInterNme = "https://api.qichacha.com/NameSearch/GetList";
        try {
            HttpHead reqHeader = new HttpHead();
            String[] autherHeader = QiChaChaUtil.RandomAuthentHeader(key, secretKey);
            reqHeader.setHeader("Token", autherHeader[0]);
            reqHeader.setHeader("Timespan", autherHeader[1]);
            String reqUri = reqInterNme.concat("?key=").concat(key).concat("&").concat("searchName=").concat(searchName);
            String tokenJson = HttpHelper.httpGet(reqUri, reqHeader.getAllHeaders());
            System.out.println(String.format("==========================>this is response:{%s}", tokenJson));
            QccJsonResult obj = JSON.parseObject(tokenJson, QccJsonResult.class);
            QccResultVO result = obj.getResult();
            List<QccCompany> data = result.getData();
            return ActionResult.success(data);
        } catch (Exception e1) {
            e1.printStackTrace();
            return ActionResult.fail("企业搜索失败!");
        }
    }

    //获取税号开票信息
    @GetMapping("/getCreditCodeNew")
    public ActionResult<?> getCreditCodeNew(@RequestParam("keyword") String keyword) {
          String reqInterNme = "https://api.qichacha.com/ECICreditCode/GetCreditCodeNew";
          String status = "";
          try {
                HttpHead reqHeader = new HttpHead();
                String[] autherHeader = QiChaChaUtil.RandomAuthentHeader(key, secretKey);
                reqHeader.setHeader("Token", autherHeader[0]);
                reqHeader.setHeader("Timespan", autherHeader[1]);
                String reqUri = reqInterNme.concat("?key=").concat(key).concat("&").concat("keyword=").concat(keyword);
                String tokenJson = HttpHelper.httpGet(reqUri, reqHeader.getAllHeaders());
                System.out.println(String.format("==========================>this is response:{%s}", tokenJson));
                status = QiChaChaUtil.FormartJson(tokenJson, "Status");
                QccJsonResult obj = JSON.parseObject(tokenJson, QccJsonResult.class);
                if (status.equals("200")) {
                    return ActionResult.success(obj.getResult());
                } else {
                    return ActionResult.fail("查询无结果");
                }
            } catch (Exception e) {
                e.printStackTrace();
                return ActionResult.fail("获取企业信息失败!");
            }
        
    }
}

5.以上控制层删除了部分业务代码,小伙伴可根据项目业务自行添加;公共返回实体类也根据自身项目框架自行变更;

6、实体类根据对应调用接口返回的json示例自行封装

譬如:税号开票信息

@Data
public class QccJsonResult {

    private String Status;
    private String Message;
    private String OrderNumber;
    private QccResultVO Result;
}

@Data
public class QccResultVO {
    /**
     * 企业名称
     */
    private String Name;
    /**
     * 统一社会信用代码(纳税人识别号)
     */
    private String CreditCode;
    /**
     * 企业类型
     */
    private String EconKind;
    /**
     * 企业状态
     */
    private String Status;
    /**
     * 地址
     */
    private String Address;
    /**
     * 联系电话
     */
    private String Tel;
    /**
     * 开户行
     */
    private String Bank;
    /**
     * 开户账号
     */
    private String BankAccount;
}

三、postman测试,实际项目应用,亲测有效!

  • 9
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值