用几行java代码读取url到字符串 [英] Read url to string in few lines of java code
本文介绍了用几行java代码读取url到字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试找到与 Groovy 等效的 Java:
I'm trying to find Java's equivalent to Groovy's:
String content = "http://www.google.com".toURL().getText();
我想将 URL 中的内容读入字符串.我不想用缓冲流和循环来污染我的代码来完成这样一个简单的任务.我查看了 apache 的 HttpClient,但也没有看到一两行实现.
I want to read content from a URL into string. I don't want to pollute my code with buffered streams and loops for such a simple task. I looked into apache's HttpClient but I also don't see a one or two line implementation.
推荐答案
既然最初的答案被接受已经过去了一段时间,有一个更好的方法:
Now that some time has passed since the original answer was accepted, there's a better approach:
String out = new Scanner(new URL("http://www.google.com").openStream(), "UTF-8").useDelimiter("\A").next();
如果你想要一个稍微完整的实现,而不是一行,这样做:
If you want a slightly fuller implementation, which is not a single line, do this:
public static String readStringFromURL(String requestURL) throws IOException
{
try (Scanner scanner = new Scanner(new URL(requestURL).openStream(),
StandardCharsets.UTF_8.toString()))
{
scanner.useDelimiter("\A");
return scanner.hasNext() ? scanner.next() : "";
}
}
这篇关于用几行java代码读取url到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文