1

使用以下链接,我正在尝试创建 URL 的 DOM 树(即返回此异常的特定 URL):

     String url="http://www.kingfisher.org/";

    Parser p = new Parser();
    SAX2DOM sax2dom ;
    org.w3c.dom.Node doc ;

    p.setFeature(Parser.namespacesFeature, false);
    p.setFeature(Parser.namespacePrefixesFeature, false);
    sax2dom = new SAX2DOM(true);
    p.setContentHandler(sax2dom);
    p.parse(new InputSource(url));
    doc = sax2dom.getDOM();

但是当我为这个 URL 运行我的程序时,它给了我一个p.parse(new InputSource(url));我不知道为什么的异常。因为到目前为止它没有任何问题。

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: http://www.kingfisher.org/
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1838)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1439)
at org.ccil.cowan.tagsoup.Parser.getInputStream(Parser.java:510)
at org.ccil.cowan.tagsoup.Parser.getReader(Parser.java:487)
at org.ccil.cowan.tagsoup.Parser.parse(Parser.java:440)
at pageparsertest.PageParserTest.main(PageParserTest.java:92)

任何提示?

4

1 回答 1

1

如果您使用 HttpURLConnection,您应该能够从 java 访问网页的请求。试试下面的代码:

String url = "http://www.kingfisher.org/";
        URL uri = new URL(url);
        HttpURLConnection httpcon = (HttpURLConnection) uri.openConnection();
        httpcon.addRequestProperty("User-Agent", "Mozilla/4.76");
        p.parse(new InputSource(httpcon.getInputStream()));
于 2015-01-03T09:28:38.153 回答