Java實現調用高德地圖逆地理編碼-htmlunit


使用htmlunit方式模擬頁面點擊操作

 

1、准備:高德地圖key申請,參考高德地圖KEY申請。在高德地圖官網找到需要實現的功能代碼。這里測試的是“逆向地理編碼方法”;

2、pom.xml文件導入相關包:

 1 <dependency>
 2     <groupId>net.sourceforge.htmlunit</groupId>
 3     <artifactId>htmlunit</artifactId>
 4     <version>2.23</version>
 5 </dependency>
 6 <dependency>
 7     <groupId>net.sourceforge.htmlunit</groupId>
 8     <artifactId>htmlunit-core-js</artifactId>
 9     <version>2.23</version>
10 </dependency>

3、因為使用Java調用,只需要實現將經緯度轉換成地址的功能,所以我們新建一個簡單的html頁面,不需要地圖加載。

  代碼如下:(其中 <script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=xxxxxxxxxxxxxx&plugin=AMap.Geocoder"></script> 中的key為您自己申請的key

 1 <!doctype html>
 2 <html lang="en">
 3 <html>
 4 <head>
 5     <meta charset="UTF-8">
 6     <meta http-equiv="X-UA-Compatible" content="IE=edge">
 7     <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
 8     <title>逆地理編碼(經緯度->地址)</title>
 9     <link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css"/>
10     <style>
11         .btn{
12             width:10rem;
13             margin-left:6.8rem;
14         }
15     </style>
16 </head>
17 <body>
18 <div class="input-card" style='width:28rem;position: absolute;left: 40%;bottom: auto;top: 40%;'>
19     <label style='color:grey'>逆地理編碼,根據經緯度獲取地址信息</label>
20     <div class="input-item">
21         <div class="input-item-prepend"><span class="input-item-text">經緯度</span></div>
22         <input id='lnglat' type="text" value='116.39,39.9'>
23     </div>
24     <div class="input-item">
25         <div class="input-item-prepend"><span class="input-item-text" >地址</span></div>
26         <input id='address' type="text" value="" >
27     </div>
28     <input id="regeo" type="button" class="btn" value="經緯度 -> 地址" >
29 </div>
30 <script src="https://a.amap.com/jsapi_demos/static/demo-center/js/demoutils.js"></script>
31 <script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=xxxxxxxxxxxxxx&plugin=AMap.Geocoder"></script>
32 <script type="text/javascript">
33     var geocoder = new AMap.Geocoder();
34     function regeoCode() {
35         var lnglat  = document.getElementById('lnglat').value.split(',');
36         geocoder.getAddress(lnglat, function(status, result) {
37             if (status === 'complete'&&result.regeocode) {
38                 var address = result.regeocode.formattedAddress;
39                 document.getElementById('address').value = address;
40             }else{
41                 log.error('根據經緯度查詢地址失敗')
42             }
43         });
44     }
45     document.getElementById("regeo").onclick = regeoCode;
46     document.getElementById('lnglat').onkeydown = function(e) {
47         if (e.keyCode === 13) {
48             regeoCode();
49             return false;
50         }
51         return true;
52     };
53 </script>
54 </body>
55 </html>

4、頁面測試成功后,使用htmlunit模擬頁面點擊。我自己封裝了工具類,代碼如下:

 

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.SilentCssErrorHandler;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlButtonInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import java.io.IOException;
public class AmapUtil {
    private static String url = "上面html的地址";
    private static WebClient webClient = new WebClient(BrowserVersion.CHROME);
    private static HtmlPage page;
    private static HtmlTextInput textField;
    private static HtmlButtonInput button;

    static {
        /* *****配置webClient******/
        //ajax
        webClient.setAjaxController(new NicelyResynchronizingAjaxController());
        //支持js
        webClient.getOptions().setJavaScriptEnabled(true);
        //忽略js錯誤
        webClient.getOptions().setThrowExceptionOnScriptError(false);
        //忽略css錯誤
        webClient.setCssErrorHandler(new SilentCssErrorHandler());
        //不執行CSS渲染
        webClient.getOptions().setCssEnabled(false);
        //超時時間
        webClient.getOptions().setTimeout(3000);
        //允許重定向
        webClient.getOptions().setRedirectEnabled(true);
        //允許cookie
        webClient.getCookieManager().setCookiesEnabled(true);
        //自定義JavaScript解析器(目的是為了不打印js存在的錯誤到日志)
        webClient.setJavaScriptEngine(new MyJavaScriptEngine(webClient));

        //開始請求網站
        try {
            page = webClient.getPage(url);
            textField = (HtmlTextInput) page.getElementById("lnglat");
            button = (HtmlButtonInput) page.getElementById("regeo");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getAddress(String lnglat){
        try  {
            textField.setText(lnglat);
            button.click();
            return  ((HtmlTextInput)page.getElementById("address")).getText();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}

 自定義JavaScript解析器:

import com.gargoylesoftware.htmlunit.InteractivePage;
import com.gargoylesoftware.htmlunit.ScriptException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebWindow;
import com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine;
import com.gargoylesoftware.htmlunit.javascript.JavaScriptErrorListener;
import com.gargoylesoftware.htmlunit.javascript.host.Window;

/**
 * 自定義JavaScript解析器(目的是為了不打印js存在的錯誤到日志)
 */
public class MyJavaScriptEngine extends JavaScriptEngine{
    public MyJavaScriptEngine(WebClient webClient) {
        super(webClient);
    }
    @Override
    protected void handleJavaScriptException(final ScriptException scriptException, final boolean triggerOnError) {
        // Trigger window.onerror, if it has been set.
        final InteractivePage page = scriptException.getPage();
        if (triggerOnError && page != null) {
            final WebWindow window = page.getEnclosingWindow();
            if (window != null) {
                final Window w = (Window) window.getScriptableObject();
                if (w != null) {
                    try {
                        w.triggerOnError(scriptException);
                    }
                    catch (final Exception e) {
                        handleJavaScriptException(new ScriptException(page, e, null), false);
                    }
                }
            }
        }
        final JavaScriptErrorListener javaScriptErrorListener = getWebClient().getJavaScriptErrorListener();
        if (javaScriptErrorListener != null) {
            javaScriptErrorListener.scriptException(page, scriptException);
        }
        if (getWebClient().getOptions().isThrowExceptionOnScriptError()) {
            throw scriptException;
        }
    }
}
View Code

5、編寫測試類測試:

    @Test
    public void test22(){
        System.out.println(AmapUtil.getAddress("116.39,36.9"));
        System.out.println(AmapUtil.getAddress("115.39,36.9"));
        System.out.println(AmapUtil.getAddress("116.39,35.9"));
        System.out.println(AmapUtil.getAddress("116.39,37.9"));
        System.out.println(AmapUtil.getAddress("116.93,37.9"));
    }

  結果如下:

 

   測試成功。HtmlUnit是用Java寫的無界面的瀏覽器,因為沒有界面,因此執行的速度還可以,它提供了一系列的API,如表單的填充,表單的提交,模仿點擊鏈接等。操作起來還是比較方便的。

 

 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM