Java 有一个有效的 URL 生成器吗?
我需要生成有效的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更新:现在您想要实现的目标更加清楚了 - 我认为这没有什么用处。你的方法应该可以,只需调试它即可。
原始答案:
事实上,您可能想使用
URI
类:您可以使用
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:
In fact, you may want to use the
URI
class instead: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 有 一种方法正是这样做的 - 它根据一组预定义的约束生成有效的 URL。
例如:
将生成一个包含 10 个 URL 的列表,如下所示:
您可以在项目的 wiki 中找到文档。
免责声明:我是这个库的开发者之一。
MockNeat has a method that does exactly this - it generates valid URLS based on a set of predefined constraints.
For example:
Will generate a list of 10 URLS that look like this:
You can find the documentation in the project's wiki.
Disclaimer: I am one of the developers of this library.