1、根据地址,得到地址的各种相应参数并取值
public static String getLocationByHttp(String adress,String city) throws IOException {
String s = "https://restapi.amap.com/v3/geocode/geo?key=你的key值&address="+adress+"&city="+city+"";
HttpEntity httpEntity = doGet(s);
return EntityUtils.toString(httpEntity);
}
@Test
public void test11() throws IOException {
String locationByHttp = getLocationByHttp("北京市朝阳区阜通东大街6号","北京");
System.out.println("locationByHttp:"+locationByHttp);
JSONObject jsonObject = JSON.parseObject(locationByHttp);
List<Map> maps = (List<Map>) jsonObject.get("geocodes");
System.out.println("geocodes:"+maps);
String country = "";
String formatted_address = "";
String neighborhood = "";
String location = "";
if(maps.size()!=0 && maps!=null){
Map map = maps.get(0);
country = String.valueOf(map.get("country"));
formatted_address = String.valueOf(map.get("formatted_address"));
neighborhood = String.valueOf(map.get("neighborhood"));
location = String.valueOf(map.get("location"));
}
System.out.println(country);
System.out.println(formatted_address);
System.out.println(neighborhood);//{"name":[],"type":[]}
JSONObject jsonKey = getJson(neighborhood);
Object name = jsonKey.get("name");
System.out.println("name:"+name);
System.out.println(location);
}
//取{"name":[],"type":[]}中name的值
public JSONObject getJson(Object string){
JSONObject jsonObject = JSON.parseObject(String.valueOf(string));
return jsonObject;
}
public static HttpEntity doGet(String url) {
//创建一个Http客户端
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
//创建一个get请求
HttpGet httpGet = new HttpGet(url);
//响应模型
CloseableHttpResponse response = null;
try {
//由客户端发送get请求
response = httpClient.execute(httpGet);
//从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
// return (List<Map>) responseEntity;
return responseEntity;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}