我正在尝试在Android应用中使用nanoHTTP来提供位于原始目录中的文件index.html。
MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
.
.
.
r = getResources();
is = r.openRawResource(R.raw.index);
MyWebServer.java
@Override
public Response serve(String uri, Method method, Map<String, String> header, Map<String, String> parms, Map<String, String> files) {
.
.
.
answer = convertStreamToString(this.mainFile);
return new NanoHTTPD.Response(answer);
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append((line + "\n"));
}
} catch (IOException e) {
Log.w("LOG", e.getMessage());
}
return sb.toString();
}
此代码首次加载index.html,但如果我刷新页面,则 answer 为空字符串。 我做错了什么?
答案 0 :(得分:0)
好的,我从这个页面发现了我的错误Getting an InputStream to read more than once, regardless of markSupported()
InputStream 只能读取一次。每当App需要为页面提供服务时,我修改了代码以重新打开InputStream。
修改后的代码在这里: MyWebServer.java
@Override
public Response serve(String uri, Method method, Map<String, String> header, Map<String, String> parms, Map<String, String> files) {
.
.
.
this.mainFile = this.mr.openRawResource(R.raw.index);
answer = convertStreamToString(this.mainFile);
return new NanoHTTPD.Response(answer);
}
并在 convertStreamToString 函数中添加 finally 块以关闭InputStream。
finally {
try {
is.close();
} catch (IOException e) {
Log.w("LOG", e.getMessage());
}
}