java - 无法通过 HtmlUnit 读取谷歌静态 map

标签 java google-maps htmlunit

我正在尝试从 Google map 读取 following URL 上的静态 map .

这在我的网络浏览器中工作正常,但是当我从 HtmlUnit 尝试这个时我得到了 UnexpectedPage 结果。有谁知道这是什么意思吗?

最佳答案

根据javadoc of UnexpectedPage ,您收到 UnexpectedPage,因为服务器返回意外的内容类型。如果检查 HtmlUnit 中返回的 header 您可以看到它包含: Content-Type=image/png

这是一个从 URL 检索图像的小应用程序:

import java.awt.Image;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

import com.gargoylesoftware.htmlunit.UnexpectedPage;
import com.gargoylesoftware.htmlunit.WebClient;

/** Small test application used to fetch a map. */
public class FetchMapSwingApp extends JFrame {
   /** Serial Id. */
   private static final long serialVersionUID = 1920071939468904323L;

   /**
    * Default constructor.
    */
   public FetchMapSwingApp() {
      // Make sure the application closes correctly
      setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

      // The map where trying to read
      String url = "http://maps.googleapis.com/maps/api/staticmap?center=55.690815,12.560678&zoom=15&size=400x500&sensor=false";
      // Fetch the image
      Image image = fetchMap(url);

      // Add the image to the JFrame and resize the frame.
      add(new JLabel(new ImageIcon(image)));
      pack();
   }

   /**
    * Fetch the image on the given URL.
    * 
    * @param url
    *            the image location
    * @return the fetched image
    */
   private Image fetchMap(String url) {
      Image image = null;
      WebClient webClient = new WebClient();
      webClient.setThrowExceptionOnScriptError(false);

      try {
         // The URL returns a png file!
         UnexpectedPage page = webClient.getPage(url);
         InputStream inputStream = page.getInputStream();
         // Read the stream to an image
         image = ImageIO.read(inputStream);
      } catch (IOException e) {
         e.printStackTrace();
      }

      return image;
   }

   /**
    * Start of the application.
    * 
    * @param args
    *            the arguments to the main method
    */
   public static void main(String args[]) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         @Override
         public void run() {
            new FetchMapSwingApp().setVisible(true);
         }
      });
   }
}

关于java - 无法通过 HtmlUnit 读取谷歌静态 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6774094/

相关文章:

java - 如何将 xml 节点(作为字符串)附加到现有的 XML 元素节点(仅使用 java 内置函数)?

java - 迭代器是快速失败的,而枚举则不是。除了 Javadoc 给出的要点之外,两者之间是否还有其他差异?

javascript - 我的谷歌地图路径符号不居中

java - 致命异常 : java. lang.OutOfMemoryError : pthread_create at com. google.maps.api

java - HtmlUnit:以特定语言从服务器请求网站

java - Android Collection ,我应该使用哪个?

java - 在 Spring MVC 中发送 HTTP POST 请求

android - 如何在 android 中使用 Google map 上的当前位置更新当前位置标记

java - 使用 htmlunit (Java) 单击链接

Java:HtmlUnit 因 JavaScript 错误而崩溃