歡迎關(guān)注微信服務(wù)號(hào):小灰熊
package com.lwz.wx.util;
//需要導(dǎo)入的包 在網(wǎng)上都是比較容易找到的
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
public class GetAddressbyJW {
/**
* @param args
*/
//用來轉(zhuǎn)化URL 的 這里用的是百度的,其他的接口也都是類似的
public String palceRequestUrl(String lat,String lng) throws UnsupportedEncodingException {
String url = "http://api.map.baidu.com/geocoder/v2/?"+ "&ak="
+ "百度給你的AK 需要設(shè)置為所以IP都可以用哦"+"&location="+lat+","+lng +"&output="+"json"+"&pois=0";
return url;
}
// 這里是獲取位置的
public String getPalace(String lat,String lng) throws Exception{
String url = palceRequestUrl(lat,lng); // 獲取完整的URL
HttpClient client = new HttpClient();
PostMethod getMethod = new PostMethod(url);
client.executeMethod(getMethod); // 用post方式提交數(shù)據(jù)
String returnStr = getMethod.getResponseBodyAsString();//鏈接返回來的信息
// 由于上面我們定義了接收返回的數(shù)據(jù)是JSON 所以這里需要對(duì)JSON 進(jìn)行解析
JSONObject jsonObj = JSONObject.fromObject(returnStr );// 把接收回來的轉(zhuǎn)成json
// System.out.println(jsonObj); //可以嘗試打印出來看下是什么
String ss= jsonObj.getString("result"); // 這個(gè)result 就是我們需要的結(jié)果
JSONObject jsonObj1 = JSONObject.fromObject(ss);
// System.out.println(jsonObj1);
// System.out.println(jsonObj1.getString("formatted_address"));
String message=jsonObj1.getString("addressComponent");
JSONObject jsonObj2 = JSONObject.fromObject(message); //這里就看你需要什么了 可以自己獲取
message=jsonObj2.getString("city");
// System.out.println(message);
return message;
}
// 簡單的main 調(diào)用
public static void main(String[] args) {
GetAddressbyJW test=new GetAddressbyJW();
try {
String ss= test.getPalace( "26.08", "119.28");
System.out.println(ss);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}