欢迎关注微信服务号:小灰熊
package com.lwz.wx.util; //需要导入的包 在网上都是比较容易找到的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 */ //用来转化URL 的 这里用的是百度的,其他的接口也都是类似的 public String palceRequestUrl(String lat,String lng) throws UnsupportedEncodingException { String url = "http://api.map.baidu.com/geocoder/v2/?"+ "&ak=" + "百度给你的AK 需要设置为所以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方式提交数据 String returnStr = getMethod.getResponseBodyAsString();//链接返回来的信息 // 由于上面我们定义了接收返回的数据是JSON 所以这里需要对JSON 进行解析 JSONObject jsonObj = JSONObject.fromObject(returnStr );// 把接收回来的转成json // System.out.println(jsonObj); //可以尝试打印出来看下是什么String ss= jsonObj.getString("result"); // 这个result 就是我们需要的结果 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 调用 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(); } } } |
|