一:需求简介.
1.1项目中天添加IP归属地查询功能,前后端分离.后端返回给前端json字符串.
1.2使用阿里云免费的IP归属地查询接口.官网一下不太好找.下面图解演示一下,尽量节省时间吧.
免费购买的.不限流免费还好用.
以上我们知道了这个接口的主要信息如下:上面那个API测试工具多试试看.
① 不限流免费的.②基于Https+GET的方式调用.③返回的是JSON数据.
二:实战演练调用.
2.1 环境准备.
SpringBoot 1.5.10.RELEASE.Maven依赖如下.阿里云提供的Demo调用中的Maven依赖比较旧了,SpringBoot框架使用出来点问题,我这些版本测试是可行的.HttpClient的版本差异有点大,注意下面的版本信息.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<!-- 开发热部署-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<version>1.5.10.RELEASE</version>
<optional>true</optional>
</dependency>
<!-- fastJson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<!-- HttpClient-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.6</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
</dependency>
2.2 SpringBoot调用网络资源服务可选HttpClient,以及框架自带的RestTemplate调用Http非常方便,但是要调用远程的Https接口就要封装一下SSL了.
根据这个接口的返回Json值,我们先建立JavaBean来接收一下吧.AIP接口调用成功与否都返回的是统一格式的JSON信息.
使用这个在线的JSON数据转换为JavaBean,快捷方便.链接
例如将下面这段JSON数据转换为JavaBean实体类.
IpMessage
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* author:
* date:
* time: 13:32
* description:第三方接口返回的IP地址信息
*/
@Setter
@Getter
@NoArgsConstructor
public class IpMessage {
/**
* 响应状态码
*/
private int ret;
/**
* 返回信息
*/
private String msg;
/**
* 赶回实体信息
*/
private DataMessage data;
/**
* 注意命名规范
*/
@JsonProperty("log_id")
/** 返回请求ID编号*/
private String logId;
}
DataMessage
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* author:
* date:
* time:
* description:第三方ip的返回实体信息
*/
@Setter
@Getter
@NoArgsConstructor
public class DataMessage {
/** 地区*/
private String area;
/** 国家*/
private String country;
/** 国家编号*/
@JsonProperty("country_id")
private String countryId;
/** 省份编号*/
@JsonProperty("region_id")
private String regionId;
/** 省份*/
private String region;
/** 城市*/
private String city;
/** 城市编号*/
@JsonProperty("city_id")
private String cityId;
/** Long类型的IP*/
@JsonProperty("long_ip")
private String longIp;
/** IP地址*/
private String ip;
/** 运营商*/
private String isp;
}
2.3 配置接口调用信息.
将接口调用信息编写为一个自定义的配置文件.提高扩展性和解决硬编码问题.
thirdip.properties
#用来配置调用第三方ip接口的调用信息
#配置Host
dockerboot.ip.host=https://api01.aliyun.venuscn.com
#配置ip路径
dockerboot.ip.path=/ip
#配置AppCode
dockerboot.ip.appcode=你的appCode
#配置请求方法
dockerboot.ip.method=get
属性注入Spring容器.
ThirdProperties
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
/**
* author:
* date:
* time: 13:52
* description: 配置第三方ip接口信息
*/
@Component
@ConfigurationProperties(prefix = "dockerboot.ip")
@PropertySource(value = "classpath:thirdip.properties")
@Setter
@Getter
public class ThirdIpPrpperties {
private String host;
private String path;
private String appcode;
private String method;
}
2.4 封装HttpClient调用Https接口.
HttpClientUtils.
import org.springframework.stereotype.Component;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
/**
* author:
* date:
* time:
* description: HttpClient调用Https接口封装.
*/
@Component
public class HttpClientUtils {
public static HttpResponse doGet(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpGet request = new HttpGet(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
/**
* post form
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param bodys
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
Map<String, String> bodys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (bodys != null) {
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (String key : bodys.keySet()) {
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
request.setEntity(formEntity);
}
return httpClient.execute(request);
}
/**
* Post String
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
/**
* Post stream
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
/**
* Put String
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
/**
* Put stream
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
/**
* Delete
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doDelete(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
StringBuilder sbUrl = new StringBuilder();
sbUrl.append(host);
if (!StringUtils.isBlank(path)) {
sbUrl.append(path);
}
if (null != querys) {
StringBuilder sbQuery = new StringBuilder();
for (Map.Entry<String, String> query : querys.entrySet()) {
if (0 < sbQuery.length()) {
sbQuery.append("&");
}
if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
sbQuery.append(query.getValue());
}
if (!StringUtils.isBlank(query.getKey())) {
sbQuery.append(query.getKey());
if (!StringUtils.isBlank(query.getValue())) {
sbQuery.append("=");
sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
}
}
}
if (0 < sbQuery.length()) {
sbUrl.append("?").append(sbQuery);
}
}
return sbUrl.toString();
}
private static HttpClient wrapClient(String host) {
HttpClient httpClient = new DefaultHttpClient();
if (host.startsWith("https://")) {
sslClient(httpClient);
}
return httpClient;
}
private static void sslClient(HttpClient httpClient) {
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);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = httpClient.getConnectionManager();
SchemeRegistry registry = ccm.getSchemeRegistry();
registry.register(new Scheme("https", 443, ssf));
} catch (KeyManagementException ex) {
throw new RuntimeException(ex);
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
}
}
IpServiceImpl封装
import com.lixing.docker.dockerboot.util.HttpClientUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import java.util.Map;
/**
* author:
* date:
* time:
* description:Service封装处理IP归属地查询
*/
@Service
public class IpServiceImpl {
public String doGet(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys) throws Exception {
HttpResponse response=null;
HttpEntity entity=null;
String respContent=null;
response = HttpClientUtils.doGet(host, path, method, headers, querys);
entity=response.getEntity();
respContent= EntityUtils.toString(entity, "UTF-8");
return respContent;
}
}
IpSearchController
import com.alibaba.fastjson.JSON;
import com.lixing.docker.dockerboot.config.ThirdIpPrpperties;
import com.lixing.docker.dockerboot.entity.IpMessage;
import com.lixing.docker.dockerboot.service.impl.IpServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
/**
* author:
* date:
* time:
* description:IP归属地查询控制器
*/
@RestController
@RequestMapping("/ip")
public class IPSearchController {
@Autowired
private ThirdIpPrpperties thirdIpPrpperties;
@Autowired
private IpServiceImpl ipServiceImpl;
@RequestMapping(value = "/search")
@ExceptionHandler(value = Exception.class)
public IpMessage search(@RequestParam("ip") String ip) throws Exception {
String host = thirdIpPrpperties.getHost();
String path = thirdIpPrpperties.getPath();
String appCode = thirdIpPrpperties.getAppcode();
String method = thirdIpPrpperties.getMethod();
Map<String, String> headers = new HashMap();
headers.put("Authorization", "APPCODE " + appCode);
Map<String, String> querys = new HashMap();
querys.put("ip", ip);
IpMessage message=new IpMessage();
// 返回字符串
String respContent = ipServiceImpl.doGet(host, path, method, headers, querys);
// JSON串解析为JavaBean
IpMessage ipMessage=JSON.parseObject(respContent, IpMessage.class);
message.setMsg(ipMessage.getMsg());
message.setData(ipMessage.getData());
message.setLogId(ipMessage.getLogId());
message.setRet(ipMessage.getRet());
System.out.println("返回的信息:"+ipMessage.getMsg());
System.out.println("返回的LogId:"+ipMessage.getLogId());
System.out.println("获取IP城市:"+(ipMessage.getData()==null?null:ipMessage.getData().getCity()));
return message;
}
}
做了全局异常处理器,在Controller层只是抛出异常即可.这个开发的接口返回的结果根据查询的ip返回内容即可.不要在Controller层try catch了,太多重复代码了,不利于统一管理了维护,加入全局异常处理,可返回人性化的页面以及描述具体的json数据.
成功了返回成功的信息,失败了也是返回统一格式的失败信息.
下面来测试一下吧:
测试一:空的IP地址.
测试二:内网IP地址.
测试三:错误格式的IP地址.
测试四:正确的IP地址.
JSON解析的结果打印如下.
至此完成了SpringBoot调用远程Https接口的过程.
简单总结:第三方API接口的调用方式,返回数据,调用方式授权(添加请求头授权信息),JavaBean接收数据,统一格式的json数据返回,异常的处理,传递参数的方式,HttpClient的版本注意问题.SpringBoot的常用注解熟练使用.