java - 使用 Nanohttpd 进行会话管理
问题描述
我正在尝试使用 Nanohttpd 创建简单的会话管理应用程序。我已使用以下项目供参考。 https://github.com/lopspower/AndroidWebServer
我有两个简单的 html 页面(sample3.html 和 sample.html),我想为输入类型创建会话name
。按下提交后,名称值应从会话值打印在sample.html上。如果用户单击Logout
按钮,则应销毁会话。我已经从参考中完成了以下代码。任何人都可以帮助我吗?提前致谢。
AndroidWebServer.java
public class AndroidWebServer extends NanoHTTPD {
public AndroidWebServer(int port) {
super(port);
}
public AndroidWebServer(String hostname, int port) {
super(hostname, port);
}
@Override
public Response serve(IHTTPSession session) {
String html=null;
try {
InputStream is = new FileInputStream("/sdcard/sample3.html");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
html = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
//return null;
}
Map<String, String> files = new HashMap<String, String>();
Method method = session.getMethod();
String postParameter="";
if (Method.POST.equals(method)) {
try {
session.parseBody(files);
} catch (IOException ioe) {
} catch (ResponseException re) {
}
}
String postBody = session.getQueryParameterString();
postParameter = session.getParms().get("name");
Log.d("Postbody",postBody+"\n"+postParameter);
if(postParameter!=null){
Log.d(TAG, "serve: inside post body ");
session.getCookies().set(new Cookie("name", postParameter));
try {
InputStream is = new FileInputStream("/sdcard/sample.html");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
html = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
}
return newFixedLengthResponse(html +" "+ session.getCookies().read("name"));
}
return newFixedLengthResponse(html);
}
}
sample3.html
<html>
<head>
<h1>Welcome to the Form</h1>
<head/>
<body>
<form action='' method='post'>
<p>Enter Name:</p><input type='text' name='name'>
<br>
<input type="submit" name="Submit">
</form>
</body></html>
`
示例.html
<html>
<body>
<p>Get name from sample.html here</p>
<input type="button" value="Logout"/>
</body>
</html>
解决方案
推荐阅读
- python - 当我在十进制到二进制递归函数中明确定义值变量时,为什么代码会给出不同的结果?
- swift - 获取当前视图控制器的情节提要 id
- c++ - 推回向量会产生荒谬的结果(C++)
- android-studio - 我想在android studio的mapbox中拖动多边形中的circleLayer,有什么解决方案吗?
- yocto - 在 RISCV 目标中的 yocto 项目中构建 consul 包
- javascript - 我想在v-for中写vue.js代码,所以这段代码应该在v-for运行时每次都运行。这可能吗?
- vue.js - 从直接链接导航时,Nuxt.js `this.$route.params.id` 未定义
- python - 用于从不同来源获取数据的 Python 异步或多线程?
- python - 带有 cx_Oracle 的 Django,调用 PL/SQL 函数需要很多时间
- google-bigquery - Google BigQuery 间歇性丢失数据