logo

Java调用企查查API实现企业信息高效查询指南

作者:Nicky2025.09.18 16:01浏览量:0

简介:本文详细介绍如何通过Java调用企查查API实现企业信息查询,涵盖API接入准备、请求封装、响应解析及异常处理等关键环节,提供完整代码示例与最佳实践。

一、企查查API接入准备

1.1 账号注册与权限申请

访问企查查开放平台官网完成企业账号注册,需提交营业执照等资质文件进行实名认证。认证通过后进入”API管理”页面,根据业务需求申请对应接口权限(如企业基础信息、工商变更记录等),平台将分配唯一的AppKey和AppSecret作为身份验证凭证。

1.2 开发环境配置

建议使用JDK 1.8+环境,添加Apache HttpClient 4.5.13和Jackson 2.13.0依赖:

  1. <!-- Maven配置示例 -->
  2. <dependencies>
  3. <dependency>
  4. <groupId>org.apache.httpcomponents</groupId>
  5. <artifactId>httpclient</artifactId>
  6. <version>4.5.13</version>
  7. </dependency>
  8. <dependency>
  9. <groupId>com.fasterxml.jackson.core</groupId>
  10. <artifactId>jackson-databind</artifactId>
  11. <version>2.13.0</version>
  12. </dependency>
  13. </dependencies>

二、API调用核心实现

2.1 请求签名生成机制

企查查API采用HMAC-SHA256算法进行请求签名,核心步骤如下:

  1. public class SignUtil {
  2. public static String generateSign(String appSecret, Map<String, String> params) {
  3. // 1. 参数按key升序排序
  4. params = params.entrySet().stream()
  5. .sorted(Map.Entry.comparingByKey())
  6. .collect(LinkedHashMap::new, (m, e) -> m.put(e.getKey(), e.getValue()), Map::putAll);
  7. // 2. 拼接待签名字符串
  8. StringBuilder sb = new StringBuilder();
  9. params.forEach((k, v) -> {
  10. if(!"sign".equals(k) && v != null) {
  11. sb.append(k).append("=").append(v).append("&");
  12. }
  13. });
  14. sb.append("key=").append(appSecret);
  15. // 3. HMAC-SHA256加密
  16. try {
  17. Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
  18. SecretKeySpec secret_key = new SecretKeySpec(appSecret.getBytes(), "HmacSHA256");
  19. sha256_HMAC.init(secret_key);
  20. byte[] bytes = sha256_HMAC.doFinal(sb.toString().getBytes());
  21. return Base64.getEncoder().encodeToString(bytes);
  22. } catch (Exception e) {
  23. throw new RuntimeException("签名生成失败", e);
  24. }
  25. }
  26. }

2.2 完整请求封装示例

  1. public class QccApiClient {
  2. private static final String API_BASE = "https://api.qcc.com";
  3. private String appKey;
  4. private String appSecret;
  5. public QccApiClient(String appKey, String appSecret) {
  6. this.appKey = appKey;
  7. this.appSecret = appSecret;
  8. }
  9. public String getEnterpriseInfo(String keyword, int page) throws IOException {
  10. // 1. 构建请求参数
  11. Map<String, String> params = new HashMap<>();
  12. params.put("appKey", appKey);
  13. params.put("keyword", keyword);
  14. params.put("page", String.valueOf(page));
  15. params.put("timestamp", String.valueOf(System.currentTimeMillis()));
  16. params.put("sign", SignUtil.generateSign(appSecret, params));
  17. // 2. 创建HTTP请求
  18. CloseableHttpClient httpClient = HttpClients.createDefault();
  19. HttpGet httpGet = new HttpGet(API_BASE + "/enterprise/search");
  20. // 3. 添加请求头
  21. httpGet.setHeader("Content-Type", "application/json");
  22. // 4. 构建URI参数
  23. URIBuilder uriBuilder = new URIBuilder(httpGet.getURI());
  24. params.forEach((k, v) -> uriBuilder.addParameter(k, v));
  25. httpGet.setURI(uriBuilder.build());
  26. // 5. 执行请求并处理响应
  27. try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
  28. if (response.getStatusLine().getStatusCode() == 200) {
  29. return EntityUtils.toString(response.getEntity());
  30. } else {
  31. throw new RuntimeException("API请求失败: " + response.getStatusLine());
  32. }
  33. }
  34. }
  35. }

三、响应数据解析与处理

3.1 JSON响应结构

典型响应数据格式如下:

  1. {
  2. "status": 200,
  3. "message": "success",
  4. "data": {
  5. "total": 125,
  6. "list": [
  7. {
  8. "name": "阿里巴巴集团",
  9. "creditCode": "91330108MA2CFE6T8U",
  10. "legalPerson": "张勇",
  11. "regCapital": "10000万人民币"
  12. }
  13. ]
  14. }
  15. }

3.2 数据解析实现

  1. public class EnterpriseInfo {
  2. private String name;
  3. private String creditCode;
  4. private String legalPerson;
  5. private String regCapital;
  6. // 省略getter/setter
  7. public static List<EnterpriseInfo> parseResponse(String json) throws IOException {
  8. ObjectMapper mapper = new ObjectMapper();
  9. JsonNode rootNode = mapper.readTree(json);
  10. if (rootNode.path("status").asInt() != 200) {
  11. throw new RuntimeException("API返回错误: " + rootNode.path("message").asText());
  12. }
  13. List<EnterpriseInfo> result = new ArrayList<>();
  14. JsonNode listNode = rootNode.path("data").path("list");
  15. for (JsonNode node : listNode) {
  16. EnterpriseInfo info = new EnterpriseInfo();
  17. info.setName(node.path("name").asText());
  18. info.setCreditCode(node.path("creditCode").asText());
  19. info.setLegalPerson(node.path("legalPerson").asText());
  20. info.setRegCapital(node.path("regCapital").asText());
  21. result.add(info);
  22. }
  23. return result;
  24. }
  25. }

四、最佳实践与异常处理

4.1 调用频率控制

建议实现令牌桶算法控制请求频率:

  1. public class RateLimiter {
  2. private final Queue<Long> queue = new ConcurrentLinkedQueue<>();
  3. private final int maxRequests;
  4. private final long timeWindow; // 毫秒
  5. public RateLimiter(int maxRequests, long timeWindow) {
  6. this.maxRequests = maxRequests;
  7. this.timeWindow = timeWindow;
  8. }
  9. public synchronized boolean tryAcquire() {
  10. long now = System.currentTimeMillis();
  11. // 清理过期请求
  12. while (!queue.isEmpty() && now - queue.peek() > timeWindow) {
  13. queue.poll();
  14. }
  15. if (queue.size() < maxRequests) {
  16. queue.offer(now);
  17. return true;
  18. }
  19. return false;
  20. }
  21. }

4.2 完整调用示例

  1. public class Main {
  2. public static void main(String[] args) {
  3. QccApiClient client = new QccApiClient("your_app_key", "your_app_secret");
  4. RateLimiter limiter = new RateLimiter(10, 1000); // 每秒10次
  5. try {
  6. if (limiter.tryAcquire()) {
  7. String response = client.getEnterpriseInfo("阿里巴巴", 1);
  8. List<EnterpriseInfo> infos = EnterpriseInfo.parseResponse(response);
  9. infos.forEach(System.out::println);
  10. } else {
  11. System.err.println("请求过于频繁,请稍后再试");
  12. }
  13. } catch (Exception e) {
  14. System.err.println("调用失败: " + e.getMessage());
  15. }
  16. }
  17. }

五、常见问题解决方案

5.1 签名验证失败

  • 检查系统时间是否同步(误差需小于5分钟)
  • 确认参数排序是否严格按ASCII码升序
  • 验证AppSecret是否正确配置

5.2 连接超时处理

  1. RequestConfig config = RequestConfig.custom()
  2. .setConnectTimeout(5000)
  3. .setSocketTimeout(5000)
  4. .build();
  5. CloseableHttpClient httpClient = HttpClients.custom()
  6. .setDefaultRequestConfig(config)
  7. .build();

5.3 数据缓存策略

建议对高频查询结果实施Redis缓存,缓存键设计示例:

  1. String cacheKey = "qcc:enterprise:" + DigestUtils.md5Hex(keyword + "_" + page);

六、安全注意事项

  1. 严格限制AppKey/AppSecret的访问权限
  2. 实现HTTPS请求强制跳转
  3. 敏感数据(如信用代码)采用脱敏处理
  4. 定期轮换API密钥

通过以上实现,开发者可以构建稳定、高效的企业信息查询系统。实际生产环境中,建议结合Spring Boot框架实现RESTful接口封装,并添加完善的日志监控体系。

相关文章推荐

发表评论