获取行政编码json,这里以山东为例,话不多说,直接开始
1.拉入所需pom
<!-- httpclientutil 开始-->
<dependency>
<groupId>org.apache.oltu.oauth2</groupId>
<artifactId>org.apache.oltu.oauth2.client</artifactId>
<version>0.31</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
<scope>provided</scope>
</dependency>
<!-- restful webService start -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
<version>2.0.3.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-client -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.19.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.7</version>
</dependency>
<!-- httplient 结束 -->
2.远程调用工具类
/**
* @author niuluda
* @version 1.0
* @date 2021/6/30 9:57
*/
import com.alibaba.fastjson.JSONObject;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import java.io.IOException;
import java.net.URI;
import java.util.*;
/**
* @author HeLiu
* @Description 请求工具类(HttpClient)
* @date 2018/11/16 10:09
*/
public class HttpClientUtil {
private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
/**
* @Description 发送get请求(带参数)
* @author HeLiu
* @date 2018/11/16 11:02
*/
public static String doGet(String url, Map<String, Object> params) {
if (!StringUtils.hasText(url)) {
return "";
}
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
try {
if (params != null && !params.isEmpty()) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
for (String key : params.keySet()) {
pairs.add(new BasicNameValuePair(key, params.get(key).toString()));
}
url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, "UTF-8"));
}
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = closeableHttpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
// 判断响应实体是否为空
if (entity != null) {
return EntityUtils.toString(entity, "UTF-8");
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 关闭流并释放资源
closeableHttpClient.close();
} catch (IOException e) {
logger.error(e.toString());
}
}
return null;
}
/**
* @Description 发送post请求(带参数)
* @author HeLiu
* @date 2018/11/16 11:02
*/
public static Map doPost(String url, Map<String, Object> param) {
try {
Client client = Client.create();
URI u = new URI(url);
WebResource resource = client.resource(u);
MultivaluedMap<String, String> params = new MultivaluedMapImpl();
Iterator i$ = param.entrySet().iterator();
while (i$.hasNext()) {
Map.Entry<String, List<String>> e = (Map.Entry) i$.next();
params.add(e.getKey(), String.valueOf(e.getValue()));
}
logger.info("查询参数:" + params.toString());
String result = resource.type(MediaType.APPLICATION_FORM_URLENCODED).post(String.class, params);
logger.info("url = :{},返回结果:{}", url, result);
JSONObject jasonObject = JSONObject.parseObject(result);
return (Map) jasonObject;
} catch (Exception e) {
logger.error("..........", e);
}
return null;
}
}
3.直接在主方法中调用,获取行政编码json,注意json格式
String keyName = "112694";//这里是key名称
String keyCode = "278c4c6f43e4ced348bb2b92829775c4";//这个是秘钥
String admAddress = "https://restapi.amap.com/v3/config/district";
Map<String, Object> params = new HashMap<>();
params.put("key", keyCode);
params.put("keywords", "山东");
params.put("subdistrict", 3);
params.put("extensions", "base");
String result = HttpClientUtil.doGet(admAddress, params);
//谷歌的gson拿到有用的属性json
JsonParser jsonParser=new JsonParser();
JsonObject asJsonObject = jsonParser.parse(result).getAsJsonObject();
String districts = asJsonObject.get("districts").toString();
return districts;
4.插入数据库,你可以写一个controller,之后再写一个递归去递归,这里我已经把json转成了对象,并递归对象插入数据库
@RequestMapping("/s")
void test() {
CityCode cityCode = JSON.parseObject(Test.s, CityCode.class);
asso(cityCode);
}
void asso(CityCode cc) {
String center = cc.getCenter();
String[] split = center.split(",");
cc.setLo(split[0]);
cc.setLa(split[1]);
//插入数据库返还主键
mapper.ins(cc);
List<CityCode> districts = cc.getDistricts();
if(districts!=null&&districts.size()>0) {
for (CityCode cityCode : districts) {
//在这里set父级主键
cityCode.setParent_id(cc.getId());
asso(cityCode);
}
}
return;
}
5.数据库表结构如下
6.实体类结构如下
public class CityCode {
private Integer id;
private String citycode;
private String adcode;
private String name;
private String center;
private String level;
private List<CityCode> districts;
private Integer parent_id;
private String lo;
private String la;
@Override
public String toString() {
return "CityCode [id=" + id + ", citycode=" + citycode + ", adcode=" + adcode + ", name=" + name + ", center="
+ center + ", level=" + level + ", districts=" + districts + ", parent_id=" + parent_id + ", lo=" + lo
+ ", la=" + la + "]";
}
public CityCode() {
super();
// TODO Auto-generated constructor stub
}
public CityCode(Integer id, String citycode, String adcode, String name, String center, String level,
List<CityCode> districts, Integer parent_id, String lo, String la) {
super();
this.id = id;
this.citycode = citycode;
this.adcode = adcode;
this.name = name;
this.center = center;
this.level = level;
this.districts = districts;
this.parent_id = parent_id;
this.lo = lo;
this.la = la;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCitycode() {
return citycode;
}
public void setCitycode(String citycode) {
this.citycode = citycode;
}
public String getAdcode() {
return adcode;
}
public void setAdcode(String adcode) {
this.adcode = adcode;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCenter() {
return center;
}
public void setCenter(String center) {
this.center = center;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public List<CityCode> getDistricts() {
return districts;
}
public void setDistricts(List<CityCode> districts) {
this.districts = districts;
}
public Integer getParent_id() {
return parent_id;
}
public void setParent_id(Integer parent_id) {
this.parent_id = parent_id;
}
public String getLo() {
return lo;
}
public void setLo(String lo) {
this.lo = lo;
}
public String getLa() {
return la;
}
public void setLa(String la) {
this.la = la;
}
}