百度~自动定位

百度~第三方自动定位API       http://lbsyun.baidu.com/index.php?title=webapi/ip-api

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.List;
/**
* 将字符拼接成字符串
* */
private String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}

/*
* URL资源解析成json对象
* */

public JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = null;
try {
is = new URL(url).openStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = JSONObject.parseObject(jsonText);
return json;
} finally {
//关闭输入流
is.close();
}
}

/*
* 自动定位,传入用户IP获取当地地址名
* */
@GetMapping("/amtLocation")
public BaseResponse amtLocation(String ip) throws JSONException, IOException{
BaseResponse response = new BaseResponse();
try{
LOGGER.info("自动定位开始");
//这里调用百度的ip定位api服务 详见 http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm
JSONObject json = readJsonFromUrl("http://api.map.baidu.com/location/ip?ak=iTrwV0ddxeFT6QUziPQh2wgGofxmWkmg&ip="+ip);
//如果IP是本地127.0.0.1或者内网IP192.168则status分别返回 1和2
String status = json.getString("status");
if(!"0".equals(status)){
response.setErrorMsg(ErrorCode.RB_FIND_LACTION_STUTAS.getDesc());
}
JSONObject content=((JSONObject) json).getJSONObject("content"); //获取json对象里的content对象
JSONObject addr_detail=((JSONObject) content).getJSONObject("address_detail");//从content对象里获取address_detail
String city = addr_detail.getString("city"); //获取市名,可以根据具体需求更改
LOGGER.info(city);
response.setData(json);
response.setSuccess(true);
return response;
}catch (Exception e){
response.setErrorMsg(ErrorCode.SYSTEM_ERROR.getDesc());
}
return response;
}
原文地址:https://www.cnblogs.com/Darkqueen/p/10524567.html