import requests
import json
r = requests.get(url='http://api.tianditu.gov.cn/geocoder?ds='
'{"keyWord":"重庆市"}&tk=这里是自己申请的tk')
print(r.json())
print(r.json()["location"]["lon"])
package com.isoftstone.web;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
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.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
/**
* @ClassName: EntCoordSyncJob
* @Description: TODO(这里用一句话描述这个类的作用)
*
*/
public class TianApi {
public static void main(String[] args) throws IOException {
String place = "北京市";
String tk = "天地图官网申请的tk";
String queryStr = "http://api.tianditu.gov.cn/geocoder?ds={'keyWord':'"+place+"'}&tk="+tk;
// URL编码{,}
queryStr = queryStr.replace("}","%7D");
queryStr = queryStr.replace("{","%7B");
// 获取http客户端
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(queryStr);
// 模拟浏览器
httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3");
CloseableHttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
if(entity != null){
String result = EntityUtils.toString(entity, "UTF-8");
System.out.println(result);
JSONObject jsonObject = JSON.parseObject(result);
// JSONObject jsonObject1 = JSONObject.parseObject(jsonObject.get("location").toString());
String location = jsonObject.get("location").toString();
JSONObject jsonObjectLocation = JSONObject.parseObject(location);
// 获取经度
String longtitude = jsonObjectLocation.get("lat").toString();
// 获取纬度
String latitude = jsonObjectLocation.get("lon").toString();
System.out.println(place+"的经度为:"+longtitude+"\r\n"+place+"的纬度为:"+latitude);
}
response.close();
}
}