在几行java代码中读取url to string [英] Read url to string in few lines of java code

查看:89
本文介绍了在几行java代码中读取url to string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到与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 to string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆