0

我正在做一个递归 url 收获..当我在源中找到一个不以“http”开头的链接时,我将它附加到当前 url。问题是当我遇到动态站点时,没有 http 的链接通常是当前 url 的新参数。例如,如果当前 url 类似于http://www.somewebapp.com/default.aspx?pageid=4088并且在该页面的源中有一个链接是 default.aspx?pageid=2111。在这种情况下,我需要做一些字符串操作;这是我需要帮助的地方。
伪代码:

if part of the link found is a contains a substring of the current url
      save the substring            
      save the unique part of the link found
replace whatever is after the substring in the current url with the unique saved part

这在java中会是什么样子?有什么不同的想法吗?谢谢。

根据评论,这是我尝试过的:

if (!matched.startsWith("http")) {
    String[] splitted = url.toString().split("/");
    java.lang.String endOfURL = splitted[splitted.length-1];
    boolean b = false;
    while (!b && endOfURL.length() > 5) { // f.bar shortest val
        endOfURL = endOfURL.substring(0, endOfURL.length()-2);
        if (matched.contains(endOfURL)) {
            matched = matched.substring(endOfURL.length()-1);
            matched = url.toString().substring(url.toString().length() - matched.length()) + matched;
            b = true;
        }
    }

效果不好。。

4

1 回答 1

1

我认为你这样做是错误的。Java 有两个类URLURI它们能够比“string bashing”解决方案更准确地解析 URL/URL 字符串。例如,URL 构造函数URL(URL, String)将在现有对象的上下文中创建一个新URL对象,而无需担心 String 是绝对 URL 还是相对 URL。你会像这样使用它:

URL currentPageUrl = ...
String linkUrlString = ...

// (Exception handling not included ...)
URL linkUrl = new URL(currentPageUrl, linkUrlString);
于 2012-10-22T00:19:42.270 回答