1.登录网址
2.添加key,
如果要使用腾讯的位置服务,必须要新建key
3.配额分配
在配额管理-->账户额度;选择你需要的服务进行配额分配;
注:如果不进行配额分配,当你调用该服务时,会出现此key每日调用量已达到上限
4.查看你需要服务的接口文档
将服务地址和请求参数都放入测试工具;例如:postman,apiFox
接口文档地址:WebService API | 腾讯位置服务 (qq.com)
因为我所需为ip定位,所以以ip定位举例;
5.通过测试工具测试接口
key值就是你刚才申请的key填入即可;
6.上代码
如果测试工具可以调通接口,那么直接在项目中写入代码,我将调用的第三方接口,封装成了一个Util类;
定位服务返回的精度不固定,因此我直接将json返回值传出
IPUtil
public class IPUtil{
private static final String TENCENT_MAP_API_KEY = "*******"; //替换你们自己的key
private static final String TENCENT_MAP_IP_API_URL = "https://apis.map.qq.com/ws/location/v1/ip";
public JSONObject ipSearch(String ip) {
String url = TENCENT_MAP_IP_API_URL + "?key=" + TENCENT_MAP_API_KEY + "&ip=" + ip;
try {
String response = sendGetRequest(url);
System.out.println("IP地址:" + ip + ",解析结果:" + response);
JSONObject jsonObject = JSONObject.parseObject(response);
int status = jsonObject.getInteger("status");
// status为0表示成功,将响应数据返回;其他异常,返回为空
if (status == 0) {
return jsonObject;
} else {
// 错误返回空
return null;
}
} catch (IOException e) {
System.err.println("解析 IP 地址时出错:" + e.getMessage());
}
return null;
}
/**
* 发送ip定位请求
* @param apiUrl
* @return
* @throws IOException
*/
private static String sendGetRequest(String apiUrl) throws IOException {
StringBuilder responseBuilder = new StringBuilder();
URL url = new URL(apiUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
responseBuilder.append(line);
}
reader.close();
return responseBuilder.toString();
}
}
Service
JSONObject jsonObject = ipUtil.ipSearch(remoteIp);
if(jsonObject!=null){
//获取省市区县并返回,因为最高定位到区县,最低定位到国家;所以要加一层判断
// 获取 result 字段的值
JSONObject resultObject = jsonObject.getJSONObject("result");
// 获取 ad_info 字段的值
JSONObject adInfoObject = resultObject.getJSONObject("ad_info");
// 判断并获取 province 字段的值
if (adInfoObject.containsKey("province")) {
String province = adInfoObject.getString("province");
}
// 判断并获取 city 字段的值
if (adInfoObject.containsKey("city")) {
String city = adInfoObject.getString("city");
}
// 判断并获取 district 字段的值
if (adInfoObject.containsKey("district")) {
String district = adInfoObject.getString("district");
}
}