gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:00:53 26 4
gpt4 key购买 nike

我正在尝试从 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com