1

使用 Google App Engine,我提出这样的请求:

URLFetchService service = URLFetchServiceFactory.getURLFetchService();
HTTPResponse response = service.fetch(request);

为了检测它是否返回 HTML,我只是将响应字符串化并查找 HTML 标记的存在。

String responseAsString = new String(response.getContent());

if (responseAsString.contains("<html>")){
    // is html
}

检测它是否是 HTML 的更好方法是什么?

此外,输入网址不一定像 example.com/page.html 那样具有描述性 - 问题是它们可能像 example.com/mystery

4

1 回答 1

2
HTTPResponse response = URLFetchServiceFactory.getURLFetchService()
            .fetch(new URL("url_to_fetch"));
List<HTTPHeader> headers = response.getHeaders();

for (HTTPHeader h : headers) {
    if (h.getName().equals("Content-Type")) {
        /*
        * could be text/html; charset=iso-8859-1.
        */
        if (h.getValue().startsWith("text/html")) {
            /* TODO do sth. */
        }
    }
}

https://developers.google.com/appengine/docs/java/javadoc/com/google/appengine/api/urlfetch/HTTPResponse#getHeaders()

您还可以检查其他MIME 类型

于 2013-07-15T21:17:52.010 回答