java IP定位 接入百度地图API

public String ipLocation(String ip) {
        HttpClient client = HttpClients.createDefault();// 创建默认http连接
        HttpPost post = new HttpPost("http://api.map.baidu.com/location/ip");// 创建一个post请求
        List paramList = new ArrayList<>();
        paramList.add(new BasicNameValuePair("ip", ip));//传递的参数
        paramList.add(new BasicNameValuePair("ak", "MzZPA1qIFLHoMi8ZbCxi0PTlgbMw8gPo"));//传递的参数
        paramList.add(new BasicNameValuePair("sn", "9b35281dac9f4b96941ce9468cbede2b"));//传递的参数
        paramList.add(new BasicNameValuePair("coor", ""));//传递的参数
        // 把参转码后放入请求实体中
        HttpEntity entitya = null;
        try {
            entitya = new UrlEncodedFormEntity(paramList, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        post.setEntity(entitya);// 把请求实体放post请求中
        HttpResponse response = null;// 用http连接去执行get请求并且获得http响应
        try {
            response = client.execute(post);
        } catch (IOException e) {
            e.printStackTrace();
        }

        HttpEntity entity = response.getEntity();// 从response中取到响实体
        String html = null;// 把响应实体转成文本
        try {
            html = EntityUtils.toString(entity);
        } catch (IOException e) {
            e.printStackTrace();
        }
        IPEntity iPEntity = Static.GSON.fromJson(html, IPEntity.class);

        try {
            return iPEntity.getContent().getAddress();
        } catch (NullPointerException npe) {

        }
//        System.out.println(html);
//
////        String a="\u5317\u4eac\u5e02";
////        System.out.println(a);
//        return html;
        return null;
    }

    public class IPEntity {
        private String address;
        private IPContentEntity content;

        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }


        public IPContentEntity getContent() {
            return content;
        }

        public void setContent(IPContentEntity content) {
            this.content = content;
        }
    }

    public class IPContentEntity {
        private String address;
        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }
    }

分享一个在线转码,IP定位小工具——头条在线工具

你可能感兴趣的:(java IP定位 接入百度地图API)