标签:city getJSONObject String jsonObject 腾讯 connection api ip null
项目中有用到了做个记录,需要的可以自己获取
public static Map<String, String> getlocation() {
URL url = null;
Map<String, String> map = new HashMap<String, String>();
HttpURLConnection connection = null;
String regEx = "[\n`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。, 、?自治区市省]";
try {//腾讯IP定位(普通)接口 10,000次/日 5次/秒
url = new URL("http://apis.map.qq.com/ws/location/v1/ip?key=");//key需要https://lbs.qq.com/faq/serverFaq/webServiceKey获取key
connection = (HttpURLConnection) url.openConnection();// 新建连接实例
connection.setConnectTimeout(3000);// 设置连接超时时间,单位毫秒
connection.setReadTimeout(3000);// 设置读取数据超时时间,单位毫秒
connection.setDoOutput(true);// 是否打开输出流 true|false
connection.setDoInput(true);// 是否打开输入流true|false
connection.setRequestMethod("GET");// 提交方法POST|GET
connection.setUseCaches(false);// 是否缓存true|false
connection.connect();// 打开连接端口
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));// 往对端写完数据对端服务器返回数据// ,以BufferedReader流来读取
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
reader.close();
JSONObject jsonObject = JSON.parseObject(buffer.toString());
if(jsonObject!=null&&!jsonObject.isEmpty()&&jsonObject.getIntValue("status")==0){
String lat=jsonObject.getJSONObject("result").getJSONObject("location").getString("lat");
String lng=jsonObject.getJSONObject("result").getJSONObject("location").getString("lng");
map.put("location",lat+','+lng);//经纬度
jsonObject.getJSONObject("result").getJSONObject("ad_info").getString("province");
String province = jsonObject.getJSONObject("result").getJSONObject("ad_info").getString("province");
String city= jsonObject.getJSONObject("result").getJSONObject("ad_info").getString("city");
city=city.replaceAll(regEx,"");
map.put("city",city);//城市
}
return map;
} catch (Exception e) {
logger.error("腾讯地图定位异常:",e);
} finally {
if (connection != null) {
connection.disconnect();// 关闭连接
}
}
return null;
}
注意:需要把你的应用ip/域名等加入白名单中~
标签:city,getJSONObject,String,jsonObject,腾讯,connection,api,ip,null 来源: https://blog.csdn.net/weixin_43937262/article/details/116145582
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。