简体   繁体   English

Java 谷歌路线 API

[英]Java Google Directions API

I am developing a Java Web application tha reads an Excel with adresses.我正在开发一个 Java Web 应用程序,它可以读取带有地址的 Excel。 (students adresses) (学生地址)

I need to get the distance from one address to each one different adress in the spreadsheet (how far from the school adress each students live)我需要在电子表格中获取从一个地址到每个不同地址的距离(每个学生住的学校地址有多远)

I'm using Dom4J library and the tests with two inputs (origin and destination) to retreive one distance is ok, but when I read the excel file and try to retreive each distance I get:我正在使用 Dom4J 库和带有两个输入(起点和终点)的测试来检索一个距离是可以的,但是当我阅读 excel 文件并尝试检索我得到的每个距离时:

Nested exception: java.io.IOException: Server returned HTTP response code: 400 for URL: https://maps.google.es/maps/api/directions/xml?origin=RUA%20JOÃO%20PESSOA,%201316,%20C/03,%20Nilopolis&destination=Rua%20João%20Pessoa,Centro&key=mykey at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1997) at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1589) at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:224) at java.xml/com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(XMLEntityManager.java:677) at java.xml/com.sun.org.apache.xerces.internal.impl.XMLVersionDetector.determineDocVersion(XMLVersionDetector.java:150) at java.xml/com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:861) at java.xml/com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.jav嵌套异常:java.io.IOException:服务器返回 HTTP 响应代码:400 用于 URL: https ://maps.google.es/maps/api/directions/xml?origin=RUA%20JOÃO%20PESSOA,%201316,%20C /03,%20Nilopolis&destination=Rua%20João%20Pessoa,Centro&key=mykey at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1997) at java.base/sun.net.www .protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1589) 在 java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:224) 在 java.xml/com.sun.org .apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(XMLEntityManager.java:677) 在 java.xml/com.sun.org.apache.xerces.internal.impl.XMLVersionDetector.determineDocVersion(XMLVersionDetector.java:150) 在 java .xml/com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:861) 在 java.xml/com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse( XML11Configuration.java a:825) at java.xml/com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141) at java.xml/com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1224) at java.xml/com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:637) at org.dom4j.io.SAXReader.read(SAXReader.java:465) at org.dom4j.io.SAXReader.read(SAXReader.java:291) at util.BibliotecaGoogle$DistanciaWS.getDocumento(BibliotecaGoogle.java:45) at util.BibliotecaGoogle$DistanciaWS.calcular(BibliotecaGoogle.java:24) at manager.Edu_turmas_impBean.determinardistancia(Edu_turmas_impBean.java:120) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:568) at a:825) 在 java.xml/com.sun.org.apache.xerces.internal 的 java.xml/com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)。 org.dom4j.io 上的 java.xml/com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:637) 上的 parser.AbstractSAXParser.parse(AbstractSAXParser.java:1224)。 SAXReader.read(SAXReader.java:465) at org.dom4j.io.SAXReader.read(SAXReader.java:291) at util.BibliotecaGoogle$DistanciaWS.getDocumento(BibliotecaGoogle.java:45) at util.BibliotecaGoogle$DistanciaWS.calcular (BibliotecaGoogle.java:24) 在 manager.Edu_turmas_impBean.determinardistancia(Edu_turmas_impBean.java:120) 在 java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 在 java.base/jdk.internal.reflect.NativeMethodAccessorImpl .invoke(NativeMethodAccessorImpl.java:77) 在 java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在 java.base/java.lang.reflect.Method.invoke(Method.java:568 ) 在 org.apache.el.parser.AstValue.invoke(AstValue.java:246) at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:266) at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105) at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87) at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102) at org.primefaces.application.DialogActionListener.processAction(DialogActionListener.java:54) at javax.faces.component.UICommand.broadcast(UICommand.java:315) at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790) at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282) at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198) at javax.faces.webapp.FacesServlet.service(Fac org.apache.el.parser.AstValue.invoke(AstValue.java:246) at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:266) at com.sun.faces.facelets.el.TagMethodExpression.invoke( TagMethodExpression.java:105) 在 javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87) 在 com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102) 在 org.primefaces.application.DialogActionListener .processAction(DialogActionListener.java:54) 在 javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790) 在 javax.faces.component.UICommand.broadcast(UICommand.java:315) 在 javax.faces.component。 UIViewRoot.processApplication(UIViewRoot.java:1282) 在 com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81) 在 com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) 在 com .sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198) 在 javax.faces.webapp.FacesServlet.service(Fac esServlet.java:658) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687) a esServlet.java:658) 在 org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) 在 org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) 在 org.apache.tomcat .websocket.server.WsFilter.doFilter(WsFilter.java:53) 在 org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) 在 org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java :162) 在 org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) 在 org.apache.catalina.authenticator 的 org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)。 AuthenticatorBase.invoke(AuthenticatorBase.java:542) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) at org .apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687) t org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1726) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.base/java.lang.Thread.run(Thread.java:833) t org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) 在 org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) 在 org.apache.coyote.http11.Http11Processor.service (Http11Processor.java:382) 在 org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) 在 org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) 在 org.apache.tomcat。 util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1726) 在 org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) 在 org.apache.tomcat.util.threads.ThreadPoolExecutor。 runWorker(ThreadPoolExecutor.java:1191) 在 org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) 在 org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread. java:61) 在 java.base/java.lang.Thread.run(Thread.java:833)

Here is my code:这是我的代码:

         public static String calcular(String origem, String destino) {
            URL url;
            try {
                String urlformatada = "https://maps.google.es/maps/api/directions/xml?origin="
                        + origem + "&destination=" + destino
                        + "&key=mykey"; 
                
                url = new URL(urlformatada.replace(" ", "%20"));
     
                Document document = getDocumento(url);
     
                return analisaXml(document);
            } catch (MalformedURLException | DocumentException e) {
                e.printStackTrace();
            }
            return "";
        }
     
        @SuppressWarnings("rawtypes")
        public static String analisaXml(Document document) {
            List list = document
                    .selectNodes("//DirectionsResponse/route/leg/distance/text");
     
            Element element = (Element) list.get(list.size() - 1);
     
            return element.getText();
        }
     
        public static Document getDocumento(URL url) throws DocumentException {
            SAXReader reader = new SAXReader();
            Document document = reader.read(url);
            return document;
        }

You need to fully URL-encode the origem and destino params.您需要对origemdestino参数进行完全 URL 编码。 When you paste the URL in Chrome, it knows what to do and encodes what it must, but the Java library does not.当您将 URL 粘贴到 Chrome 中时,它知道要做什么并对必须执行的操作进行编码,但 Java 库不知道。

Try like this:试试这样:

String urlformatada = "https://maps.google.es/maps/api/directions/xml?origin="
                        + URLEncoder.encode( origem, "UTF-8" ) + "&destination="
                        + URLEncoder.encode( destino, "UTF-8" ) + "&key=mykey"; 

and then remove the .replace(" ", "%20") part - it's unnecessary.然后删除.replace(" ", "%20")部分 - 这是不必要的。

Thank you for the reply.感谢您的答复。 The problem was that when you fill the command on the browser it makes the proper treatments, but when you encapsulate in your code you need to treat all.问题是,当您在浏览器上填写命令时,它会进行适当的处​​理,但是当您封装在代码中时,您需要处理所有内容。 For example: these characters "ç", ":", "ã" in the origin or destination.例如:这些字符“ç”、“:”、“ã”在始发地或目的地。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM