Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

android

http

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?

like image 632
Lori Avatar asked Sep 25 '19 16:09

Lori


People also ask

What does the delimiter do in Java?

In Java, delimiters are the characters that split (separate) the string into tokens. Java allows us to define any characters as a delimiter.

What does use delimiter mean?

A delimiter is a sequence of one or more characters for specifying the boundary between separate, independent regions in plain text, mathematical expressions or other data streams. An example of a delimiter is the comma character, which acts as a field delimiter in a sequence of comma-separated values.

What does Scanner delimiter do?

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

Which of these methods is used for setting the delimiting pattern to a pattern?

The useDelimiter(String pattern) method of java. util. Scanner class Sets this scanner's delimiting pattern to a pattern constructed from the specified String.


1 Answers

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();
}
like image 181
Andreas Avatar answered Sep 30 '22 07:09

Andreas