开发者

There is a URL valid generator for Java?

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.

开发者_JS百科

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;
    }
}


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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜