Java 有一个有效的 URL 生成器吗?

发布于 2024-11-06 01:33:51 字数 1357 浏览 2 评论 0原文

我需要生成有效的 URL。

示例:我传递网址:google.com 。生成器返回 http://google.com/

有些浏览器会这样做。我尝试做自己的算法,但失败了。

另一个例子: www.yadayadayada.com/../test 返回 http://www.yadayadayada.com/test/

public String generateValidURL(String url) {
    int pos = 0;        
    try {
        url = url.trim();
        url = url.replaceAll(" ", "%20");
        if (url.startsWith("http") && (!url.substring(4).startsWith("://"))) {
            for (int i = 4; i < 7; i++) {
                if ((url.charAt(i) == '/') || (url.charAt(i) == ':')) {
                    pos = i;
                }
            }
            url = url.substring(pos + 1);
        }
        if(url.startsWith("https")){
            url = url.replace("https", "http");
        }
        if (!url.startsWith("http")) {
            url = "http://" + url;
        }
        if (!url.substring(7).contains("/")) {
            url += "/";
        }
        url = url.replace(",", ".");
        url = url.replace("../", "/");
        url = url.substring(0, 7) + url.substring(7).replace("//", "/");            
        return url;
    } catch (Exception e) {
        System.out.println("Error generating valid URL : " + e);
        return null;
    }
}

I need generate valid URLs.

Example: I pass the url: google.com . The generator returns http://google.com/ .

Some browsers do this. I tried do my own algorithm, but has fails.

Another example: www.yadayadayada.com/../test returns http://www.yadayadayada.com/test/

public String generateValidURL(String url) {
    int pos = 0;        
    try {
        url = url.trim();
        url = url.replaceAll(" ", "%20");
        if (url.startsWith("http") && (!url.substring(4).startsWith("://"))) {
            for (int i = 4; i < 7; i++) {
                if ((url.charAt(i) == '/') || (url.charAt(i) == ':')) {
                    pos = i;
                }
            }
            url = url.substring(pos + 1);
        }
        if(url.startsWith("https")){
            url = url.replace("https", "http");
        }
        if (!url.startsWith("http")) {
            url = "http://" + url;
        }
        if (!url.substring(7).contains("/")) {
            url += "/";
        }
        url = url.replace(",", ".");
        url = url.replace("../", "/");
        url = url.substring(0, 7) + url.substring(7).replace("//", "/");            
        return url;
    } catch (Exception e) {
        System.out.println("Error generating valid URL : " + e);
        return null;
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

許願樹丅啲祈禱 2024-11-13 01:33:51

更新:现在您想要实现的目标更加清楚了 - 我认为这没有什么用处。你的方法应该可以,只需调试它即可。

原始答案:

URL url = new URL("http", domain, "/");
String output = url.toExternalForm();

事实上,您可能想使用 URI 类:

URI uri = new URI("http", "google.com", "/test", null);

您可以使用 uri.resolve("../relativePath") 它将得到解析。但请记住,您的 /../test == /test 示例不正确(您必须手动处理这种情况)

Update: now that is is clearer what you want to achieve - I don't think there's an utility for that. Your method should do, just debug it.

Original answer:

URL url = new URL("http", domain, "/");
String output = url.toExternalForm();

In fact, you may want to use the URI class instead:

URI uri = new URI("http", "google.com", "/test", null);

You can use uri.resolve("../relativePath") and it will get resolved. But have in mind that your example with /../test == /test is not proper (you'd have to handle this case manually)

好菇凉咱不稀罕他 2024-11-13 01:33:51

MockNeat一种方法正是这样做的 - 它根据一组预定义的约束生成有效的 URL。

例如:

MockNeat m = MockNeat.threadLocal();

m.urls()
  .scheme(HTTP) // all the URLS have a HTTP scheme
//.auth() -- can include auth information in the URL
  .domain(POPULAR) // only popular domain names can be used 
  .host(ADVERB_VERB) 
  .ports(80, 8080, 8090) // only the following ports can be used
  .list(10) 
  .consume(System.out::println);

将生成一个包含 10 个 URL 的列表,如下所示:

[http://www.tenthlyassays.net:8090, http://www.aflamecurr.io:8080, http://www.thirdlygirth.org:8080, http://www.foreprobates.net:8090, http://www.pokilyrile.org:80, http://www.cheerfullyapprizings.net:8090, http://www.whistlinglyunsettles.info:80, http://www.gratistrichinized.io:8080, http://www.sternwardssnuffle.gov:8090, http://www.yesterdaynix.edu:8090]

您可以在项目的 wiki 中找到文档。

免责声明:我是这个库的开发者之一。

MockNeat has a method that does exactly this - it generates valid URLS based on a set of predefined constraints.

For example:

MockNeat m = MockNeat.threadLocal();

m.urls()
  .scheme(HTTP) // all the URLS have a HTTP scheme
//.auth() -- can include auth information in the URL
  .domain(POPULAR) // only popular domain names can be used 
  .host(ADVERB_VERB) 
  .ports(80, 8080, 8090) // only the following ports can be used
  .list(10) 
  .consume(System.out::println);

Will generate a list of 10 URLS that look like this:

[http://www.tenthlyassays.net:8090, http://www.aflamecurr.io:8080, http://www.thirdlygirth.org:8080, http://www.foreprobates.net:8090, http://www.pokilyrile.org:80, http://www.cheerfullyapprizings.net:8090, http://www.whistlinglyunsettles.info:80, http://www.gratistrichinized.io:8080, http://www.sternwardssnuffle.gov:8090, http://www.yesterdaynix.edu:8090]

You can find the documentation in the project's wiki.

Disclaimer: I am one of the developers of this library.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文