以下 Http 请求代码中的“\\A”分隔符有何作用?

Lor*_*ori 5 java android http

所以我正在关注 Udacity 上的这个 Android 应用程序开发课程,但我很困惑。以下函数返回一个 JSON,但我不明白分隔符 ("\A") 的用法。

  public static String getResponseFromHttpUrl(URL url) throws IOException {
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        try {
            InputStream in = urlConnection.getInputStream();

            Scanner scanner = new Scanner(in);
            scanner.useDelimiter("\\A");

            boolean hasInput = scanner.hasNext();
            if (hasInput) {
                return scanner.next();
            } else {
                return null;
            }
        } finally {
            urlConnection.disconnect();
        }
    }
Run Code Online (Sandbox Code Playgroud)

那么 \A 分隔符的作用是什么?它是如何工作的?

And*_*eas 9

useDelimiter(String pattern)方法采用正则表达式模式作为参数。

正则表达式模式记录Pattern类的 javadoc 中。

\A模式在边界匹配器块中列出:

\A - 输入的开始

这基本上指定没有分隔符,因此该next()方法将读取整个输入流。

问题代码等价于以下使用Apache Commons IO库的代码:

HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
    String content = IOUtils.toString(urlConnection.getInputStream(), Charset.defaultCharset());
    return (content.isEmpty() ? null : content);
} finally {
    urlConnection.disconnect();
}
Run Code Online (Sandbox Code Playgroud)