笔者这里使用的是ali的开放api 的url , 所以需要使用htttp 形式调用,
至于调用方式多种多样, 我这里挑一个就很简单的 Rest Template来使用
配置RestTemplate
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
/**
* @author huang
*/
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(15000);
factory.setReadTimeout(5000);
return factory;
}
}
Service封装
注意这里面的各种类都没啥特殊的 , 如果缺少某些json类啥的都可以直接引入
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
/**
* @author huang
*/
@Component
public class AliService {
private static final Logger log = LoggerFactory.getLogger(AliService.class);
private static final String URL = "https://ip.taobao.com/outGetIpInfo?ip=IPaddress&&accessKey=alibaba-inc";
@Autowired
RestTemplate restTemplate;
public JSONObject getAreaFromAli(String ip) {
String url = StringUtils.replace(URL, "IPaddress", ip);
String body = null;
log.info("请求Ali获取ip地址所属地区,url:{}", url);
try {
ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
body = forEntity.getBody();
} catch (Exception e) {
log.error("请求Ali获取ip地址所属地区异常:" + e.getMessage(), e);
}
if (StringUtils.isBlank(body)) {
log.error("请求Ali获取ip地址所属地区异常,返回为空");
return null;
}
JSONObject res = JSON.parseObject(body, JSONObject.class);
if (0 != res.getInteger("code")) {
log.error("请求Ali根据ip获取地区信息失败,状态码:{}", res.getInteger("code"));
return null;
}
return res.getJSONObject("data");
}
}