当前位置: 移动技术网 > IT编程>开发语言>Java > java调用百度定位api服务获取地理位置示例

java调用百度定位api服务获取地理位置示例

2019年07月22日  | 移动技术网IT编程  | 我要评论

复制代码 代码如下:

package test;

import java.io.bufferedreader;
import java.io.ioexception;
import java.io.inputstream;
import java.io.inputstreamreader;
import java.io.reader;
import java.net.url;
import java.nio.charset.charset;

import org.json.jsonexception;
import org.json.jsonobject;
/**
 * java根据url获取json对象
 * @author openks
 * @since 2013-7-16
 * 需要添加java-json.jar才能运行
 */
public class getplacebyip {

  private static string readall(reader rd) throws ioexception {
    stringbuilder sb = new stringbuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
      sb.append((char) cp);
    }
    return sb.tostring();
  }

  public static jsonobject readjsonfromurl(string url) throws ioexception, jsonexception {
    inputstream is = new url(url).openstream();
    try {
      bufferedreader rd = new bufferedreader(new inputstreamreader(is, charset.forname("utf-8")));
      string jsontext = readall(rd);
      jsonobject json = new jsonobject(jsontext);
      return json;
    } finally {
      is.close();
     // system.out.println("同时 从这里也能看出 即便return了,仍然会执行finally的!");
    }
  }

  public static void main(string[] args) throws ioexception, jsonexception {
   //这里调用百度的ip定位api服务 详见 http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm
    jsonobject json = readjsonfromurl("http://api.map.baidu.com/location/ip?ak=f454f8a5efe5e577997931cc01de3974&ip=202.198.16.3");
    system.out.println(json.tostring());
    system.out.println(((jsonobject) json.get("content")).get("address"));
  }
}


 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网