Android NanoHTTPD作为服务器问题

博主在尝试使用Android NanoHTTPD作为服务器处理HTTP请求时遇到问题,服务器端在`is.read(buf, 0, bufsize)`处阻塞。服务端能够监听到连接,但在解析客户端发送的数据时出现阻塞,无法正常读取输入流。代码中展示了服务端和客户端的实现细节,包括NanoHTTPD的serve方法和自定义的解析函数parseBody,以及客户端使用HttpPost发送JSON数据。" 121122442,11035595,掌握SaltStack:常用模块详解,"['SaltStack', 'Linux管理', '系统自动化']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如题,最近在学Android发布http,遇到问题了,服务端可以监听到连接,可是在解析数据的时候它一直在阻塞,有谁知道嘛?
上代码:

服务端:

@Override
public Response serve(IHTTPSession session) {
// TODO Auto-generated method stub
super.serve(session);
try {
System.out.println(session.getUri());
System.out.println("XXXXXXXXXXXXXXXXXXXXXXXXXXX");
String body = parseBody(session);//在这里阻塞了
System.out.println(body);
JSONObject request = new JSONObject(body);
//String action = request.getString("action");
JSONObject o = new JSONObject();
o.put("result", "gfdgf");
String resp = o.toString();
Response response = new Response(Response.Status.OK,"application/json",resp);
System.out.println("result:"+resp);
return response;
} catch(JSONException e) {
e.printStackTrace();
return null;
}
}

private String parseBody(IHTTPSession session) {

String body = null;
try {
InputStream is = session.getInputStream();
if (is == null) {
//Log.i(TAG, "session.getInputStream() is null!");
System.out.println("getInputStream is null");
return body;
}
System.out.println("getInputStream not null");
// 假定消息不超过8192byte
int bufsize = 8192;
System.out.println("read start");
byte[] buf = new byte[bufsize];

int rlen = is.read(buf, 0, bufsize);        //发现在这里阻塞了!
System.out.println("read end");
if (rlen <= 0) {
//Log.i(TAG, "http body read 0 byte!");
System.out.println("read is null");
return null;
}
System.out.println("read not null,len is"+rlen);
ByteArrayInputStream hbis = new ByteArrayInputStream(buf, 0, rlen);
BufferedReader hin = new BufferedReader(new InputStreamReader(hbis));
body = hin.readLine();
System.out.println("body is"+body);
return body;
} catch (IOException ioe) {
ioe.printStackTrace();
}
return null;
}


客户端:

class MySender extends Thread {
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
try {
JSONObject request = new JSONObject();
request.put("action", et.getText().toString());
HttpPost post = new HttpPost("http://"+ip+":8888");
post.setEntity(new StringEntity(request.toString()));
HttpResponse response = new DefaultHttpClient().execute(post);
String res = EntityUtils.toString(response.getEntity());
Message msg = new Message();
msg.obj = res;
handler.sendMessage(msg);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值