What does the "\\A" delimiter do in the following Http Request code?

Lori :

So I'm following this Android app dev course on Udacity and I'm confused. The following function returns a JSON, but I don't understand the usage of the delimiter ("\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();
        }
    }

So what the \A delimiter does? How does it work?

Andreas :

The useDelimiter(String pattern) method takes a regex pattern as parameter.

Regex patterns are documented in the javadoc of the Pattern class.

The \A pattern is listed in the Boundary matchers block:

\A - The beginning of the input

This basically specifies that there is no delimiter, so the next() method will read the entire input stream.

The question code is equivalent to the following code using the Apache Commons IO library:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=307959&siteId=1