68 lines
2.7 KiB
Java
68 lines
2.7 KiB
Java
package com.bao.dating.service.impl;
|
||
|
||
import com.bao.dating.common.ip2location.Ip2LocationConfig;
|
||
import com.bao.dating.pojo.vo.IpLocationVO;
|
||
import com.bao.dating.service.Ip2LocationClientService;
|
||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||
import org.apache.http.client.config.RequestConfig;
|
||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||
import org.apache.http.client.methods.HttpGet;
|
||
import org.apache.http.client.utils.URIBuilder;
|
||
import org.apache.http.impl.client.CloseableHttpClient;
|
||
import org.apache.http.impl.client.HttpClients;
|
||
import org.apache.http.util.EntityUtils;
|
||
import org.springframework.beans.factory.annotation.Autowired;
|
||
import org.springframework.stereotype.Component;
|
||
import org.springframework.stereotype.Service;
|
||
|
||
import java.net.URI;
|
||
|
||
@Service
|
||
public class Ip2LocationClientServiceImpl implements Ip2LocationClientService {
|
||
@Autowired
|
||
private Ip2LocationConfig ip2LocationConfig;
|
||
|
||
// Jackson的ObjectMapper,用于JSON解析
|
||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||
|
||
/**
|
||
* 调用API并只返回核心位置信息
|
||
* @param ip 要查询的IP地址
|
||
* @return 精简的位置信息实体类
|
||
* @throws Exception 异常
|
||
*/
|
||
@Override
|
||
public IpLocationVO getIpLocation(String ip) throws Exception {
|
||
// 1. 构建请求URL
|
||
URIBuilder uriBuilder = new URIBuilder(ip2LocationConfig.getUrl());
|
||
uriBuilder.addParameter("key", ip2LocationConfig.getKey());
|
||
if (ip != null && !ip.trim().isEmpty()) {
|
||
uriBuilder.addParameter("ip", ip);
|
||
}
|
||
URI uri = uriBuilder.build();
|
||
|
||
// 2. 配置超时时间(逻辑和之前一致)
|
||
RequestConfig requestConfig = RequestConfig.custom()
|
||
.setConnectTimeout(ip2LocationConfig.getTimeout())
|
||
.setSocketTimeout(ip2LocationConfig.getTimeout())
|
||
.build();
|
||
|
||
// 3. 发送请求并解析响应
|
||
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
|
||
HttpGet httpGet = new HttpGet(uri);
|
||
httpGet.setConfig(requestConfig);
|
||
|
||
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
|
||
if (response.getStatusLine().getStatusCode() == 200) {
|
||
String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
|
||
// 核心:将完整JSON解析为只包含位置信息的VO类
|
||
return objectMapper.readValue(jsonStr, IpLocationVO.class);
|
||
} else {
|
||
throw new RuntimeException("调用API失败,状态码:" + response.getStatusLine().getStatusCode());
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
}
|