zoukankan      html  css  js  c++  java
  • 百度地图api根据详细地址反查坐标

    用百度地图api根据详细地址反查坐标

    /**
     * 根据详细地址反查坐标
     * @param args
     */
    public static void main(String[] args) {
          String address = "南开-南开区西湖道与南丰路交口东侧-南开区西湖里小区-2号楼-1门-3层";
          JSONObject j = RestUtil.httpRequest(new RestParam("http://api.map.baidu.com/geocoder/v2/?output=json&ak=1XjLLEhZhQNUzd93EjU5nOGQ&address="+address,"GET", "", "http", "", ""));
          JSONObject resuleObject = JSONObject.fromObject(j.getString("result"));
          String location = resuleObject.get("location")+"";
          JSONObject locObject = JSONObject.fromObject(location);
          String lng = locObject.get("lng")+"";
          String lat = locObject.get("lat")+"";
          System.out.println(resuleObject.toString());
          System.out.println("经度:"+lng+" "+"纬度:"+lat);
    }

    rest请求通用接口工具类:RestUtil

    package com.ksource.pwlp.util;
    
    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.net.Authenticator;
    import java.net.ConnectException;
    import java.net.HttpURLConnection;
    import java.net.InetSocketAddress;
    import java.net.PasswordAuthentication;
    import java.net.Proxy;
    import java.net.URL;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    
    import javax.net.ssl.HostnameVerifier;
    import javax.net.ssl.HttpsURLConnection;
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.SSLSession;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509TrustManager;
    
    import net.sf.json.JSONObject;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    /**
     * rest请求通用接口工具类
     * 
     * @author ardo
     */
    public class RestUtil {
        
    private static Logger log = LoggerFactory.getLogger(RestUtil.class);
        
        /**
         * 发起http/https请求并获取结果
         */
        public static JSONObject httpRequest(RestParam restParam) {
            JSONObject jsonObject = null;
            // 创建代理服务器
            InetSocketAddress addr = null;
            Proxy proxy = null;
            boolean ifProxyModel = restParam.getIfProxy()!=null && restParam.getIfProxy()!="" && "TRUE".equals(restParam.getIfProxy());
            
            if(ifProxyModel){
                addr = new InetSocketAddress(restParam.getProxyAddress(), Integer.parseInt(restParam.getProxyPort()));
                proxy = new Proxy(Proxy.Type.HTTP, addr); // http 代理
                Authenticator.setDefault(new MyAuthenticator(restParam.getProxyUser(), restParam.getProxyPassWord()));// 设置代理的用户和密码
            }
            
            try {
                
                URL url = new URL(restParam.getReqUrl());
                if("https".equals(restParam.getReqHttpsModel())){
                    TrustManager[] tmCerts = new javax.net.ssl.TrustManager[1];
                    tmCerts[0] = new SimpleTrustManager();
                    try {
                        SSLContext sslContext = SSLContext.getInstance("SSL");
                        sslContext.init(null, tmCerts, null);
                        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    
                        HostnameVerifier hostnameVerifier = new SimpleHostnameVerifier();
                        HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    HttpsURLConnection httpUrlConn = null;
                    if(ifProxyModel){
                        httpUrlConn = (HttpsURLConnection) url.openConnection(proxy);
                    }else{
                        httpUrlConn = (HttpsURLConnection) url.openConnection();
                    }
                    
                    //httpUrlConn.setSSLSocketFactory(ssf);
                    jsonObject = ardoHttpsURLConnection(httpUrlConn, restParam.getReqMethod(), 
                        restParam.getReqContent(), restParam.getSessionId());
                }else{
                    HttpURLConnection httpUrlConn = null;
                    if(ifProxyModel){
                        httpUrlConn = (HttpURLConnection) url.openConnection(proxy);
                    }else{
                        httpUrlConn = (HttpURLConnection) url.openConnection();
                    }
                    jsonObject = ardoHttpURLConnection(httpUrlConn, restParam.getReqMethod(), 
                        restParam.getReqContent(), restParam.getSessionId());
                    
                }
                
            } catch (ConnectException ce) {
                log.error("API server connection timed out.");
                log.error("【rest连接异常信息】"+ce.getMessage());
            } catch (Exception e) {
                log.error("API https or http request error:{}", e);
                log.error("【rest异常信息】"+e.getMessage());
            }
            return jsonObject;
        }
        
        /**
         * http请求方法
         * @param httpUrlConn 请求路径
         * @param requestMethod 请求类型POST|GET
         * @param outputStr 请求内容
         * @param sessionId sessionId(非必填)
         * @return JSONObject类型数据
         */
        public static JSONObject ardoHttpURLConnection(HttpURLConnection httpUrlConn, 
                String requestMethod, String outputStr, String sessionId){
            JSONObject jsonObject = null;
            StringBuffer buffer = new StringBuffer();
            try {
                
                //httpUrlConn = (HttpURLConnection) url.openConnection();
    
                httpUrlConn.setDoOutput(true);
                httpUrlConn.setDoInput(true);
                httpUrlConn.setUseCaches(false);
                
                if(sessionId!=null && sessionId!=""){
                    httpUrlConn.setRequestProperty("Cookie", "JSESSIONID="+sessionId);
                }
                
                // 设置请求方式GET/POST
                httpUrlConn.setRequestMethod(requestMethod);
    
                if ("GET".equalsIgnoreCase(requestMethod))
                    httpUrlConn.connect();
    
                // 当有数据需要提交时
                if (null != outputStr) {
                    OutputStream outputStream = httpUrlConn.getOutputStream();
                    //注意编码格式,防止中文乱码
                    outputStream.write(outputStr.getBytes("UTF-8"));
                    outputStream.close();
                }
    
                // 将返回的输入流转换成字符串
                InputStream inputStream = httpUrlConn.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    
                String str = null;
                while ((str = bufferedReader.readLine()) != null) {
                    buffer.append(str);
                }
                bufferedReader.close();
                inputStreamReader.close();
                // 释放资源
                inputStream.close();
                inputStream = null;
                httpUrlConn.disconnect();
                jsonObject = JSONObject.fromObject(buffer.toString());
            } catch (ConnectException ce) {
                log.error("API server connection timed out.");
                log.error("【rest http连接异常信息】"+ce.getMessage());
            } catch (Exception e) {
                log.error("API http request error:{}", e);
                log.error("【rest http异常信息】"+e.getMessage());
            }
            return jsonObject;
        }
        
        /**
         * https请求方法
         * @param httpUrlConn 请求路径
         * @param requestMethod 请求类型POST|GET
         * @param outputStr 请求内容
         * @param sessionId sessionId(非必填)
         * @return JSONObject类型数据
         */
        public static JSONObject ardoHttpsURLConnection(HttpsURLConnection httpUrlConn, 
                String requestMethod, String outputStr, String sessionId){
            JSONObject jsonObject = null;
            StringBuffer buffer = new StringBuffer();
            try {
                
                //httpUrlConn = (HttpsURLConnection) url.openConnection();
                httpUrlConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
                httpUrlConn.setDoOutput(true);
                httpUrlConn.setDoInput(true);
                httpUrlConn.setUseCaches(false);
                
                if(sessionId!=null && sessionId!=""){
                    httpUrlConn.setRequestProperty("Cookie", "JSESSIONID="+sessionId);
                }
                
                //设置请求方式GET/POST
                httpUrlConn.setRequestMethod(requestMethod);
                httpUrlConn.setRequestProperty("Content-Type", "application/json");
                
                if ("GET".equalsIgnoreCase(requestMethod))
                    httpUrlConn.connect();
    
                // 当有数据需要提交时
                if (null != outputStr) {
                    OutputStream outputStream = httpUrlConn.getOutputStream();
                    //注意编码格式,防止中文乱码
                    outputStream.write(outputStr.getBytes("UTF-8"));
                    outputStream.close();
                }
    
                // 将返回的输入流转换成字符串
                InputStream inputStream = httpUrlConn.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    
                String str = null;
                while ((str = bufferedReader.readLine()) != null) {
                    buffer.append(str);
                }
                bufferedReader.close();
                inputStreamReader.close();
                // 释放资源
                inputStream.close();
                inputStream = null;
                httpUrlConn.disconnect();
                jsonObject = JSONObject.fromObject(buffer.toString());
            } catch (ConnectException ce) {
                log.error("API server connection timed out.");
                log.error("【rest https连接异常信息】"+ce.getMessage());
            } catch (Exception e) {
                log.error("API https request error:{}", e);
                log.error("【rest https异常信息】"+e.getMessage());
            }
            return jsonObject;
        }
        
        /**
         * 代理模式所需的认证
         * @author ardo
         *
         */
        static class MyAuthenticator extends Authenticator {
            private String user = "";
            private String password = "";
      
            public MyAuthenticator(String user, String password) {
                this.user = user;
                this.password = password;
            }
      
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, password.toCharArray());
            }
        }
        
    
        // test url
        //public static String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
        
        
        private static class SimpleTrustManager implements TrustManager, X509TrustManager {
    
            
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
                return;
            }
    
            
            public void checkServerTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
                return;
            }
    
            
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        }
        
        private static class SimpleHostnameVerifier implements HostnameVerifier {
    
            
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
    
        }
        
        public static void main(String[] args) {
            //Test for rest
            RestUtil.httpRequest(new RestParam("http://121.56.130.23/ardosms/v2email", "POST", "发送内容,可以是html文本", 
                    "http", "", "TRUE", "proxy.xxx", "8080", "du...", "1zc3..."));
        }
    }

    该bean作为RestUtil类方法参数:RestParam

    package com.ksource.pwlp.util;
    /**
     * rest bean
     * 
     * 该bean作为RestUtil类方法参数
     * @author ardo
     * 
     */
    public class RestParam {
        /**
         * 请求url路径
         */
        private String reqUrl;
        /**
         * 请求类型"POST"或"GET"
         */
        private String reqMethod;
        /**
         * 请求内容
         */
        private String reqContent;
        /**
         * 请求模式"https"或"http"(默认http)
         */
        private String reqHttpsModel;
        /**
         * 该值为空时不设置,不为空时设置
         */
        private String sessionId;
        /**
         * 是否开启代理模式(默认FALSE)"TRUE":开启;"FALSE":不开启;设为TRUE时需要配置以下几项参数
         */
        private String ifProxy;
        /**
         * 代理地址
         */
        private String proxyAddress;
        /**
         * 代理端口
         */
        private String proxyPort;
        /**
         * 代理账号
         */
        private String proxyUser;
        /**
         * 代理密码
         */
        private String proxyPassWord;
        
        
        public RestParam() {
            super();
        }
        
        /**
         * 全参型构造方法
         * @param reqUrl
         * @param reqMethod
         * @param reqContent
         * @param reqHttpsModel
         * @param sessionId
         * @param ifProxy
         * @param proxyAddress
         * @param proxyPort
         * @param proxyUser
         * @param proxyPassWord
         */
        public RestParam(String reqUrl, String reqMethod, String reqContent,
                String reqHttpsModel, String sessionId, String ifProxy,
                String proxyAddress, String proxyPort, String proxyUser,
                String proxyPassWord) {
            super();
            this.reqUrl = reqUrl;
            this.reqMethod = reqMethod;
            this.reqContent = reqContent;
            this.reqHttpsModel = reqHttpsModel;
            this.sessionId = sessionId;
            this.ifProxy = ifProxy;
            this.proxyAddress = proxyAddress;
            this.proxyPort = proxyPort;
            this.proxyUser = proxyUser;
            this.proxyPassWord = proxyPassWord;
        }
        
        /**
         * 一般型构造方法
         * @param reqUrl
         * @param reqMethod
         * @param reqContent
         * @param reqHttpsModel
         * @param sessionId
         */
        public RestParam(String reqUrl, String reqMethod, String reqContent,
                String reqHttpsModel, String sessionId) {
            super();
            this.reqUrl = reqUrl;
            this.reqMethod = reqMethod;
            this.reqContent = reqContent;
            this.reqHttpsModel = reqHttpsModel;
            this.sessionId = sessionId;
        }
        
        /**
         * 简约型构造方法
         * @param reqUrl
         * @param reqMethod
         * @param reqContent
         * @param reqHttpsModel
         */
        public RestParam(String reqUrl, String reqMethod, String reqContent,
                String reqHttpsModel) {
            super();
            this.reqUrl = reqUrl;
            this.reqMethod = reqMethod;
            this.reqContent = reqContent;
            this.reqHttpsModel = reqHttpsModel;
        }
        
        /**
         * 阿杜代理型构造方法
         * [if ifProxy=="ardo" then auto proxy]
         * @param reqUrl
         * @param reqMethod
         * @param reqContent
         * @param reqHttpsModel
         * @param sessionId
         * @param ifProxy
         */
        public RestParam(String reqUrl, String reqMethod, String reqContent,
                String reqHttpsModel, String sessionId, String ifProxy) {
            super();
            this.reqUrl = reqUrl;
            this.reqMethod = reqMethod;
            this.reqContent = reqContent;
            this.reqHttpsModel = reqHttpsModel;
            this.sessionId = sessionId;
            if("ardo".equals(ifProxy)){
                this.ifProxy = "TRUE";
                this.proxyAddress = "proxy.xxx";
                this.proxyPort = "8080";
                this.proxyUser = "du...";
                this.proxyPassWord = "1zc3...";
            }
        }
        
        /**
         * 请求url路径
         */
        public String getReqUrl() {
            return reqUrl;
        }
        public void setReqUrl(String reqUrl) {
            this.reqUrl = reqUrl;
        }
        
        /**
         * 请求类型"POST"或"GET"
         */
        public String getReqMethod() {
            return reqMethod;
        }
        public void setReqMethod(String reqMethod) {
            this.reqMethod = reqMethod;
        }
        
        /**
         * 请求内容
         */
        public String getReqContent() {
            return reqContent;
        }
        public void setReqContent(String reqContent) {
            this.reqContent = reqContent;
        }
        
        /**
         * 请求模式"https"或"http"(默认http)
         */
        public String getReqHttpsModel() {
            return reqHttpsModel;
        }
        public void setReqHttpsModel(String reqHttpsModel) {
            this.reqHttpsModel = reqHttpsModel;
        }
        
        /**
         * 该值为空时不设置,不为空时设置
         */
        public String getSessionId() {
            return sessionId;
        }
        public void setSessionId(String sessionId) {
            this.sessionId = sessionId;
        }
        
        /**
         * 是否开启代理模式(默认FALSE)"TRUE":开启;"FALSE":不开启;设为TRUE时需要配置以下几项参数
         */
        public String getIfProxy() {
            return ifProxy;
        }
        public void setIfProxy(String ifProxy) {
            this.ifProxy = ifProxy;
        }
        
        /**
         * 代理地址
         */
        public String getProxyAddress() {
            return proxyAddress;
        }
        public void setProxyAddress(String proxyAddress) {
            this.proxyAddress = proxyAddress;
        }
        
        /**
         * 代理端口
         */
        public String getProxyPort() {
            return proxyPort;
        }
        public void setProxyPort(String proxyPort) {
            this.proxyPort = proxyPort;
        }
        
        /**
         * 代理账号
         */
        public String getProxyUser() {
            return proxyUser;
        }
        public void setProxyUser(String proxyUser) {
            this.proxyUser = proxyUser;
        }
        
        /**
         * 代理密码
         */
        public String getProxyPassWord() {
            return proxyPassWord;
        }
        public void setProxyPassWord(String proxyPassWord) {
            this.proxyPassWord = proxyPassWord;
        }
        
        
    }

    输出结果:

    {"location":{"lng":117.17403,"lat":39.124958},"precise":1,"confidence":80,"comprehension":95,"level":"地产小区"}
    经度:117.17403 纬度:39.124958
  • 相关阅读:
    第八章 多线程编程
    Linked List Cycle II
    Swap Nodes in Pairs
    Container With Most Water
    Best Time to Buy and Sell Stock III
    Best Time to Buy and Sell Stock II
    Linked List Cycle
    4Sum
    3Sum
    Integer to Roman
  • 原文地址:https://www.cnblogs.com/henuyuxiang/p/12980864.html
Copyright © 2011-2022 走看看