「\\ Aは、」区切り文字次のHTTPリクエスト・コードで何をしますか?

ロリ:

だから私はUdacityに、このAndroidアプリdevのコースを以下だと私は混乱しています。次の関数は、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();
        }
    }

だから、\区切り文字は何をしますか?それがどのように動作しますか?

アンドレアス:

useDelimiter(String pattern)メソッドは、パラメータとして正規表現パターンをとります。

正規表現パターンがされている文書のjavadocのPatternクラス。

\Aパターンに記載されている境界のmatcherブロック。

\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();
}

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=314366&siteId=1