1.1项目中天添加IP归属地查询功能,前后端分离.后端返回给前端json字符串.
1.2使用阿里云免费的IP归属地查询接口
以上我们知道了这个接口的主要信息如下:上面那个API测试工具多试试看.
① 不限流免费的.②基于Https+GET的方式调用.③返回的是JSON数据.
SpringBoot 1.5.10.RELEASE.Maven依赖如下.阿里云提供的Demo调用中的Maven依赖比较旧了,SpringBoot框架使用出来点问题,我这些版本测试是可行的.HttpClient的版本差异有点大,注意下面的版本信息.
com.alibaba
fastjson
1.2.47
org.apache.httpcomponents
httpclient
4.5.3
org.apache.httpcomponents
httpcore
4.4.6
commons-lang
commons-lang
2.6
org.projectlombok
lombok
1.16.18
根据这个接口的返回Json值,我们先建立JavaBean来接收一下吧.AIP接口调用成功与否都返回的是统一格式的JSON信息.
使用这个在线的JSON数据转换为JavaBean,快捷方便.链接
例如将下面这段JSON数据转换为JavaBean实体类.
IpMessage.java
第三方接口返回的IP地址信息
package com.example.entity;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* @author: wangxiaobo
* @create: 2020-08-24 23:07
* description:第三方接口返回的IP地址信息
**/
@Setter
@Getter
@NoArgsConstructor
public class IpMessage {
/**
* 赶回实体信息
*/
private DataMessage data;
/**
* 响应状态码
*/
private int ret;
/**
* 返回信息
*/
private String msg;
/**
* 注意命名规范
*/
@JsonProperty("log_id")
/** 返回请求ID编号*/
private String logId;
}
DataMessage.java
第三方ip的返回实体信息
package com.example.entity;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* @author: wangxiaobo
* @create: 2020-08-24 23:13
* description:第三方ip的返回实体信息
**/
@Setter
@Getter
@NoArgsConstructor
public class DataMessage {
/** IP地址*/
private String ip;
/** Long类型的IP*/
@JsonProperty("long_ip")
private String longIp;
/** 运营商*/
private String isp;
/** 地区*/
private String area;
/** 省份编号*/
@JsonProperty("region_id")
private String regionId;
/** 省份*/
private String region;
/** 城市编号*/
@JsonProperty("city_id")
private String cityId;
/** 城市*/
private String city;
/** 国家编号*/
@JsonProperty("country_id")
private String countryId;
/** 国家*/
private String country;
}
application.yml
server:
port: 8089
#用来配置调用第三方ip接口的调用信息
#配置Host
system:
host: https://api01.aliyun.venuscn.com
#配置ip路径
path: /ip
#配置AppCode
appcode: 你的appCode
#配置请求方法
method: get
属性注入Spring容器.
ThirdProperties.java
package com.example.config;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author: wangxiaobo
* @create: 2020-08-24 23:34
* description: 配置第三方ip接口信息
**/
@Component
@ConfigurationProperties(prefix="system")
@Setter
@Getter
public class ThirdIpPrpperties {
private String host;
private String path;
private String appcode;
private String method;
}
HttpClientUtils.java
package com.example.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
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.config.Registry;
import org.apache.http.config.RegistryBuilder;
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.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
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.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
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.Arrays;
import java.util.List;
import java.util.Map;
/**
* @author: wangxiaobo
* @create: 2020-08-24 23:41
* description: HttpClient调用Https接口封装.
* http请求工具类
**/
@Component
public class HttpClientUtils {
/**
* get
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doGet(String host, String path, String method,
Map headers,
Map querys) throws Exception {
HttpClient httpClient = wrapClient (host,path);
HttpGet request = new HttpGet (buildUrl(host, path, querys));
for (Map.Entry e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
/**
* post form
* @param host
* @param path
* @param headers
* @param querys
* @param bodys
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path,
Map headers,
Map querys,
Map bodys)
throws Exception {
HttpClient httpClient = wrapClient(host,path);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (bodys != null) {
List nameValuePairList = new ArrayList ();
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 headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path,
Map headers,
Map querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host,path);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry 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 headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path,
Map headers,
Map querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host,path);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry 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 headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path,
Map headers,
Map querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host,path);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry 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 headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path,
Map headers,
Map querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host,path);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry 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 headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doDelete(String host, String path,
Map headers,
Map querys)
throws Exception {
HttpClient httpClient = wrapClient(host,path);
HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
for (Map.Entry e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
/**
* 构建请求的 url
* @param host
* @param path
* @param querys
* @return
*/
private static String buildUrl(String host, String path, Map querys)
throws UnsupportedEncodingException {
StringBuilder sbUrl = new StringBuilder();
//append(String str)字符串连接
if (!StringUtils.isBlank(host)) {
sbUrl.append (host);
}
if (!StringUtils.isBlank(path)) {
sbUrl.append(path);
}
if (null != querys) {
StringBuilder sbQuery = new StringBuilder();
for (Map.Entry 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();
}
/**
* 获取 HttpClient
* @param host
* @param path
* @return
*/
private static HttpClient wrapClient(String host, String path) {
//DefaultHttpClient过时的替换
//HttpClient httpClient = new DefaultHttpClient();
// HttpClient client = HttpClientBuilder.create ().build ();
// if (host.startsWith ("https://")) {
// if (host != null && host.startsWith ("https://")) {
// return sslClient ();
// } else if (StringUtils.isBlank (host) && path != null && path.startsWith ("https://")) {
// return sslClient ();
// }
// }
// return client;
// }
HttpClient httpClient = HttpClientBuilder.create().build();
if (host != null && host.startsWith("https://")) {
return sslClient();
}else if (StringUtils.isBlank(host) && path != null && path.startsWith("https://")) {
return sslClient();
}
return httpClient;
}
/**
* 在调用SSL之前需要重写验证方法,取消检测SSL
* 创建ConnectionManager,添加Connection配置信息
* @return HttpClient 支持https
*
*/
private static HttpClient sslClient() {
try {
// 在调用SSL之前需要重写验证方法,取消检测SSL
X509TrustManager trustManager = new X509TrustManager() {
@Override public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override public void checkClientTrusted(X509Certificate[] xcs, String str) {}
@Override public void checkServerTrusted(X509Certificate[] xcs, String str) {}
};
SSLContext ctx = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
ctx.init(null, new TrustManager[] { trustManager }, null);
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
// 创建Registry
RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT)
.setExpectContinueEnabled(Boolean.TRUE).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM,AuthSchemes.DIGEST))
.setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
Registry socketFactoryRegistry = RegistryBuilder.create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https",socketFactory).build();
// 创建ConnectionManager,添加Connection配置信息
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
CloseableHttpClient closeableHttpClient = HttpClients.custom().setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig).build();
return closeableHttpClient;
} catch (KeyManagementException ex) {
throw new RuntimeException(ex);
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
}
/**
* 将结果转换成JSONObject
* @param httpResponse
* @return
* @throws IOException
*/
public static JSONObject getJson(HttpResponse httpResponse) throws IOException {
HttpEntity entity = httpResponse.getEntity();
String resp = EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity);
return JSON.parseObject(resp);
}
}
IpServiceImpl.java 封装
package com.example.service;
import com.example.utils.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: wangxiaobo
* @create: 2020-08-25 12:01
* description:Service封装处理IP归属地查询
**/
@Service
public class IpServiceImpl {
public String doGet(String host ,String path, String method,
Map headers,
Map querys)throws Exception{
HttpResponse response = HttpClientUtils.doGet (host, path, method, headers, querys);
HttpEntity entity = response.getEntity ();
String respContent = EntityUtils.toString (entity,"UTF-8");
return respContent;
}
}
IpSearchController.java
package com.example.controller;
import com.alibaba.fastjson.JSON;
import com.example.config.ThirdIpPrpperties;
import com.example.entity.DataMessage;
import com.example.entity.IpMessage;
import com.example.service.IpServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.xml.crypto.Data;
import java.util.HashMap;
import java.util.Map;
/**
* @author: wangxiaobo
* @create: 2020-08-25 12:07
* 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 headers = new HashMap ();
headers.put ("Authorization", "APPCODE " +appCode);
Map querys = new HashMap();
querys.put ("ip",ip);
IpMessage message = new IpMessage ();
// DataMessage dataMessage =new DataMessage ();
// 返回字符串
String respContent = ipServiceImpl.doGet (host, path, method, headers, querys);
// JSON串解析为JavaBean
IpMessage ipMessage = JSON.parseObject (respContent ,IpMessage.class);
//DataMessage dataMessage1 = JSON.parseObject (respContent , DataMessage.class);
// dataMessage.setCity (dataMessage.getCity ());
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城市:"+(dataMessage1.getCity ()));
System.out.println("获取IP城市:"+(ipMessage.getData()==null?null:ipMessage.getData().getCity()));
System.out.println ("获取IP的省份:"+(ipMessage.getData ()==null?null:ipMessage.getData ().getRegion ()));
return message;
}
}
做了全局异常处理器,在Controller层只是抛出异常即可.这个开发的接口返回的结果根据查询的ip返回内容即可.不要在Controller层try catch了,太多重复代码了,不利于统一管理了维护,加入全局异常处理,可返回人性化的页面以及描述具体的json数据.
成功了返回成功的信息,失败了也是返回统一格式的失败信息.
1.正确的IP地址.
2.错误格式的IP地址.
3.内网IP地址.
4.空的IP地址.
5.JSON解析的结果打印如下.
这就是SpringBoot调用远程Https接口的过程.
简单总结:第三方API接口的调用方式,返回数据,调用方式授权(添加请求头授权信息),JavaBean接收数据,统一格式的json数据返回,异常的处理,传递参数的方式,HttpClient的版本注意问题.SpringBoot的常用注解熟练使用.