我正在 Android 中实现基于 REST 的 HTTP 服务器。服务器响应 GET、DELETE 和 POST 请求。两个 android 设备使用 HTTP Post 进行通信(我正在使用一项服务,其中一个设备一直在侦听一个端口并发布到下一个设备,并且这一直在进行)。
我正在使用 Mozilla Poster 测试 GET 和 DELETE。我应该添加一个单独的套接字/端口来处理相同的问题吗?因为当我现在尝试时,有时我会收到超时错误或找不到响应。但是,我可以在 Logcat 窗口中看到服务器响应。请帮我。处理 GET 请求的代码:
if(method.equals("GET"))
{
if(checkFileExisting())
{
BufferedReader reader = new BufferedReader(new FileReader(new File(getFilesDir()+File.separator+"script.json")));
String read;
StringBuilder builder = new StringBuilder("");
while((read = reader.readLine()) != null)
{
builder.append(read);
}
String JSONContents = builder.toString();
reader.close();
JSONObject jsonObject;
try {
jsonObject = new JSONObject(JSONContents);
String name = jsonObject.getString("name");
JSONObject stateObject = jsonObject.getJSONObject("state");
String stateValue = stateObject.getString("value");
if(name.equals(target))
{
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
response.setEntity(new StringEntity("State is:" + stateValue));
conn.sendResponseHeader(response);
conn.sendResponseEntity(response);
}
else
{
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 404, "Not Found");
response.setEntity(new StringEntity("The requested resource " + target + " could not be found due to mismatch!!"));
conn.sendResponseHeader(response);
conn.sendResponseEntity(response);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else
{
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 404, "Not Found");
response.setEntity(new StringEntity("The requested resource " + target + " could not be found!!"));
conn.sendResponseHeader(response);
conn.sendResponseEntity(response);
}
}