java:
package com.example.address;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import org.apache.commons.lang.StringUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created By: hdx
* Date: 2020-06-04 09:05
*/
public class address {
private static String read(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 readJson(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 = read(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void main(String[] args) throws IOException, JSONException {
//这里调用百度的ip定位api服务 详见 http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm ak 需要自己注册一下
JSONObject json = readJson("http://api.map.baidu.com/location/ip?ak=gZOLCTs0kPxF5WQZWI3ZYBfuBc5ZX1HYv&coor=bd09ll&ip=47.xxx.xxx.110");
System.out.println(json.toString());
JSONObject json1 = readJson("http://api.map.baidu.com/geocoder?location=36.09928993,118.52766339&output=json&key=E4805d16x520de693a3fe707cdc962045");
System.out.println(json1.toString());
}
}
ak 和 key 不对,运行时 需要 自己去 http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm 创建 应用
ip需要填写公网ip
百度地址 : http://lbsyun.baidu.com/apiconsole/key#/home
pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.vaadin.external.google</groupId>
<artifactId>android-json</artifactId>
<version>0.0.20131108.vaadin1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.vaadin.external.google</groupId>
<artifactId>android-json</artifactId>
<version>0.0.20131108.vaadin1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>