所以我在 Udacity 上学习这个 Android 应用程序开发类(class),但我很困惑。 以下函数返回一个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();
}
}
那么\A 定界符的作用是什么?它是如何工作的?
最佳答案
useDelimiter(String pattern)
方法采用正则表达式模式作为参数。
正则表达式模式在 Pattern
的 javadoc 中记录类。
\A
模式列在 Boundary matchers 中 block :
\A
- The beginning of the input
这基本上指定没有定界符,所以 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();
}
关于java - "\\A"分隔符在以下 Http Request 代码中的作用是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58102714/