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

该博客展示了如何使用Java从指定URL获取JSON数据,并进行解析。通过调用百度的IP定位API,程序演示了读取网络响应并转换为JSONObject的过程。此示例强调了网络I/O和JSON处理的基础知识。
摘要由CSDN通过智能技术生成

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"));

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值