我有这个Web服务器类:
private class WebServer extends NanoHTTPD {
public WebServer()
{
super(PORT);
Log.i("myTag", "THIS IS RUNNING2");
}
@Override
public Response serve(String uri, Method method, Map<String, String> header, Map<String, String> parameters, Map<String, String> files) {
Log.i("myTag", "THIS IS RUNNING3");
String answer = "";
try {
// Open file from SD Card
File root = Environment.getExternalStorageDirectory();
FileReader index = new FileReader(root.getAbsolutePath() + "/www/index.html");
BufferedReader reader = new BufferedReader(index);
String line = "";
while ((line = reader.readLine()) != null) {
answer += line;
}
reader.close();
} catch(IOException ioe) {
Log.w("httpd", answer);
}
return new NanoHTTPD.Response(answer);
}
}
我在网上找到的(http://devnote1.blogspot.com/2016/05/android-studio-nanohttpd.html)。我按照教程进了T。
我设置了3个日志,这些日志应该在标签下的logcat中可见,&#34; myTag&#34;我注意到serve()方法中的第三个日志没有输出。在我的android工作室中,serve方法有一行贯穿它,工具提示说:&#34;覆盖不推荐使用的方法,导入fi.iki.elonen.NanoHTTPD&#39;。任何人都可以帮我解决这个问题吗?
我正在使用这种依赖:
compile 'com.nanohttpd:nanohttpd-webserver:2.1.1'
当我进入浏览器并输入localhost:8080时,它不会给我一个无法访问的网站&#39;错误,所以我相信一些Web服务器的东西工作。任何帮助表示赞赏。谢谢
答案 0 :(得分:0)
问题在于权限。您必须在运行时允许权限: https://developer.android.com/training/permissions/requesting.html
如果您只是在清单中设置它,您仍将获得拒绝权限。
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
if (permissionCheck == 0) {
Log.i("perm", "granted");
} else if (permissionCheck == -1){
Log.i("perm", "denied");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
你必须覆盖它:
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
Log.i("perm", "request code = " + requestCode);
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.i("perm", "GRANTED");
}
}
return;
}