我有一个Java程序,我正在编写一个接受URL作为参数的方法。有没有办法让方法返回与我传递的URL相关联的'robots.txt'文件(例如https://www.google.com/robots.txt)文件的副本?如何访问网站的robots.txt
在此先感谢!
我有一个Java程序,我正在编写一个接受URL作为参数的方法。有没有办法让方法返回与我传递的URL相关联的'robots.txt'文件(例如https://www.google.com/robots.txt)文件的副本?如何访问网站的robots.txt
在此先感谢!
我现在几乎没有任何关于robot.txt的内容,但我似乎记得,您始终将其存储在根路径中。所以我相信像下面的例子中getRobot()
的方法应该能正常运行为您提供:
import java.io.InputStream;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.IOUtils;
public class Robots {
public static void main(String[] args) {
System.out.println(new Robots().getRobot("http://www.google.de/q?Stack Overflow"));
}
public String getRobot(String url) {
Pattern p = Pattern.compile("^(http(s?)://([^/]+))");
Matcher m = p.matcher(url);
if (m.find()) {
System.out.println(m.group(1));
try (InputStream in = new URL(m.group(1) + "/robots.txt").openStream()) {
return IOUtils.toString(in);
} catch (Exception e) {
e.printStackTrace();
}
}
return "no robots allowed";
}
}
退房main()
的工作示例
你可以添加一些简单的URL解析,以确保URL我们始终只服务器URL。我认为即使是简单的正则表达式也可以做到。 –
所以它只是传递*任何* URL?是的,这是简单的正则表达式。 – Jan
工程就像一个魅力,谢谢! –
请出示你有什么/核对答案。 – Jan