Java调用企查查API实现企业信息高效查询指南
2025.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依赖:
<!-- Maven配置示例 -->
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.0</version>
</dependency>
</dependencies>
二、API调用核心实现
2.1 请求签名生成机制
企查查API采用HMAC-SHA256算法进行请求签名,核心步骤如下:
public class SignUtil {
public static String generateSign(String appSecret, Map<String, String> params) {
// 1. 参数按key升序排序
params = params.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.collect(LinkedHashMap::new, (m, e) -> m.put(e.getKey(), e.getValue()), Map::putAll);
// 2. 拼接待签名字符串
StringBuilder sb = new StringBuilder();
params.forEach((k, v) -> {
if(!"sign".equals(k) && v != null) {
sb.append(k).append("=").append(v).append("&");
}
});
sb.append("key=").append(appSecret);
// 3. HMAC-SHA256加密
try {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(appSecret.getBytes(), "HmacSHA256");
sha256_HMAC.init(secret_key);
byte[] bytes = sha256_HMAC.doFinal(sb.toString().getBytes());
return Base64.getEncoder().encodeToString(bytes);
} catch (Exception e) {
throw new RuntimeException("签名生成失败", e);
}
}
}
2.2 完整请求封装示例
public class QccApiClient {
private static final String API_BASE = "https://api.qcc.com";
private String appKey;
private String appSecret;
public QccApiClient(String appKey, String appSecret) {
this.appKey = appKey;
this.appSecret = appSecret;
}
public String getEnterpriseInfo(String keyword, int page) throws IOException {
// 1. 构建请求参数
Map<String, String> params = new HashMap<>();
params.put("appKey", appKey);
params.put("keyword", keyword);
params.put("page", String.valueOf(page));
params.put("timestamp", String.valueOf(System.currentTimeMillis()));
params.put("sign", SignUtil.generateSign(appSecret, params));
// 2. 创建HTTP请求
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(API_BASE + "/enterprise/search");
// 3. 添加请求头
httpGet.setHeader("Content-Type", "application/json");
// 4. 构建URI参数
URIBuilder uriBuilder = new URIBuilder(httpGet.getURI());
params.forEach((k, v) -> uriBuilder.addParameter(k, v));
httpGet.setURI(uriBuilder.build());
// 5. 执行请求并处理响应
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity());
} else {
throw new RuntimeException("API请求失败: " + response.getStatusLine());
}
}
}
}
三、响应数据解析与处理
3.1 JSON响应结构
典型响应数据格式如下:
{
"status": 200,
"message": "success",
"data": {
"total": 125,
"list": [
{
"name": "阿里巴巴集团",
"creditCode": "91330108MA2CFE6T8U",
"legalPerson": "张勇",
"regCapital": "10000万人民币"
}
]
}
}
3.2 数据解析实现
public class EnterpriseInfo {
private String name;
private String creditCode;
private String legalPerson;
private String regCapital;
// 省略getter/setter
public static List<EnterpriseInfo> parseResponse(String json) throws IOException {
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(json);
if (rootNode.path("status").asInt() != 200) {
throw new RuntimeException("API返回错误: " + rootNode.path("message").asText());
}
List<EnterpriseInfo> result = new ArrayList<>();
JsonNode listNode = rootNode.path("data").path("list");
for (JsonNode node : listNode) {
EnterpriseInfo info = new EnterpriseInfo();
info.setName(node.path("name").asText());
info.setCreditCode(node.path("creditCode").asText());
info.setLegalPerson(node.path("legalPerson").asText());
info.setRegCapital(node.path("regCapital").asText());
result.add(info);
}
return result;
}
}
四、最佳实践与异常处理
4.1 调用频率控制
建议实现令牌桶算法控制请求频率:
public class RateLimiter {
private final Queue<Long> queue = new ConcurrentLinkedQueue<>();
private final int maxRequests;
private final long timeWindow; // 毫秒
public RateLimiter(int maxRequests, long timeWindow) {
this.maxRequests = maxRequests;
this.timeWindow = timeWindow;
}
public synchronized boolean tryAcquire() {
long now = System.currentTimeMillis();
// 清理过期请求
while (!queue.isEmpty() && now - queue.peek() > timeWindow) {
queue.poll();
}
if (queue.size() < maxRequests) {
queue.offer(now);
return true;
}
return false;
}
}
4.2 完整调用示例
public class Main {
public static void main(String[] args) {
QccApiClient client = new QccApiClient("your_app_key", "your_app_secret");
RateLimiter limiter = new RateLimiter(10, 1000); // 每秒10次
try {
if (limiter.tryAcquire()) {
String response = client.getEnterpriseInfo("阿里巴巴", 1);
List<EnterpriseInfo> infos = EnterpriseInfo.parseResponse(response);
infos.forEach(System.out::println);
} else {
System.err.println("请求过于频繁,请稍后再试");
}
} catch (Exception e) {
System.err.println("调用失败: " + e.getMessage());
}
}
}
五、常见问题解决方案
5.1 签名验证失败
- 检查系统时间是否同步(误差需小于5分钟)
- 确认参数排序是否严格按ASCII码升序
- 验证AppSecret是否正确配置
5.2 连接超时处理
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(5000)
.setSocketTimeout(5000)
.build();
CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(config)
.build();
5.3 数据缓存策略
建议对高频查询结果实施Redis缓存,缓存键设计示例:
String cacheKey = "qcc:enterprise:" + DigestUtils.md5Hex(keyword + "_" + page);
六、安全注意事项
- 严格限制AppKey/AppSecret的访问权限
- 实现HTTPS请求强制跳转
- 敏感数据(如信用代码)采用脱敏处理
- 定期轮换API密钥
通过以上实现,开发者可以构建稳定、高效的企业信息查询系统。实际生产环境中,建议结合Spring Boot框架实现RESTful接口封装,并添加完善的日志监控体系。
发表评论
登录后可评论,请前往 登录 或 注册