我只是用这个java代码检查URL的链接吗?

use*_*504 5 java url hyperlink

我有一个方法,它接收URL并找到该页面上的所有链接.但是我担心如果只检查链接,就像我检查链接是否正常工作一样,有些链接看起来很奇怪.例如,如果我检查www.google.com上的链接,我会得到6个断开的链接,这些链接不返回http状态代码,而是说该链接断开了"没有协议".我只是不认为谷歌会在其主页上有任何断开的链接.其中一个损坏的链接的示例是:/ preferences?hl = zh_我无法在google主页上看到此链接的位置.我很好奇,如果我只检查链接或是否有可能我提取不应该是链接的代码?

以下是检查链接的URL的方法:

public static List getLinks(String uriStr) {

    List result = new ArrayList<String>();
    //create a reader on the html content
    try{
        System.out.println("in the getlinks try");
    URL url = new URI(uriStr).toURL();
    URLConnection conn = url.openConnection();
    Reader rd = new InputStreamReader(conn.getInputStream());

    // Parse the HTML
    EditorKit kit = new HTMLEditorKit();
    HTMLDocument doc = (HTMLDocument)kit.createDefaultDocument();
    kit.read(rd, doc, 0);

    // Find all the A elements in the HTML document
    HTMLDocument.Iterator it = doc.getIterator(HTML.Tag.A);
    while (it.isValid()) {
        SimpleAttributeSet s = (SimpleAttributeSet)it.getAttributes();

        String link = (String)s.getAttribute(HTML.Attribute.HREF);
        if (link != null) {
                // Add the link to the result list
                System.out.println(link);
            //System.out.println("link print finished");
            result.add(link);
        }
        //System.out.println(link);
        it.next();
    }
    }
Run Code Online (Sandbox Code Playgroud)

Fra*_*ulo 1

您返回的链接没有任何问题。

查看您的代码,您正在提取属性href,在您的示例中,该属性来自元素:

<a  class=gbmt href="/preferences?hl=en">Search settings</a>
Run Code Online (Sandbox Code Playgroud)

(如果您单击“设置”右下角,您可以看到此链接,应该会弹出一个包含多个链接的列表)

正如您所看到的,该href属性仅包含/preferences?hl=en,这只是使其成为一个相对链接。完整的 url 是您当前所在页面的地址 + href。在这种情况下:

http://www.google.com/preferences?hl=en
Run Code Online (Sandbox Code Playgroud)

如果 url 是相对的,您只需调整代码以在方法的参数前面添加。