根据ip获得经纬度

在项目开发过程中需要根据IP地址得到经纬度,将代码贴出:

public class LocationUtil {
   public static String[] getLocation(String ip) {
      String[] returnString=new String[2];
      try {
         Map map = new HashMap();
         map.put("ip", ip);
         map.put("ak", "z8cPGX5TKKrZOYbrAlgYcnSYHFm6o5cE");
         map.put("coor", "bd09ll");
         String StringReturn = HttpRequest.sendPost("http://api.map.baidu.com/location/ip", map);
         
         JSONObject jobject=JSONObject.fromObject(StringReturn);
            logger.info(StringReturn);
            if(jobject.getInt("status")==0) {
               JSONObject point= jobject.getJSONObject("content").getJSONObject("point");
               String x=point.getString("x");
               String y=point.getString("y");
               returnString= new String[] { x, y };
            }
            
      } catch (Exception e) {
         e.printStackTrace();
      }
      return returnString;

   }
 
public static String sendPost(String url, Map<String, String> paramMap) {
   CloseableHttpClient httpclient = HttpClients.createDefault();
   HttpPost httpPost = new HttpPost(url);
   CloseableHttpResponse response = null;
   InputStreamReader ins = null;
   BufferedReader in = null;
   StringBuffer result = new StringBuffer();
   HttpEntity entity = null;
   try {
      // 拼接参数
      List<NameValuePair> nvps = new ArrayList<NameValuePair>();
      for (String param : paramMap.keySet()) {
         nvps.add(new BasicNameValuePair(param, paramMap.get(param)));
      }
      httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
      response = httpclient.execute(httpPost);
      if(response.getStatusLine().getStatusCode()!=200){
         //throw new Exception("请求异常");
         return null;
      }
      entity = response.getEntity();
      // 消耗掉response
      // 定义BufferedReader输入流来读取URL的响应
      ins = new InputStreamReader(entity.getContent(), "UTF-8");
      in = new BufferedReader(ins);
      String line;
      while ((line = in.readLine()) != null) {
         result.append(line);
      }

      return result.toString();
   } catch (Exception e) {
      log.error("post请求异常", e);

   } finally {
      close(httpclient, response, ins, in, entity);
   }
   return null;
}
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值