[英]Handling HTTP Get/ Delete Android using REST
I m implementing a REST based HTTP server in Android. 我在Android中实现基于REST的HTTP服务器。 The server responds for GET, DELETE and POST requests. 服务器响应GET,DELETE和POST请求。 Two android devices communicate using HTTP Post (I m using a service, where a device keeps listening on a port and post to next device and this keeps going on). 两个android设备使用HTTP Post通信(我正在使用服务,其中设备不断监听端口并发布到下一个设备,并且这种情况一直持续)。
I m testing the GET and DELETE using Mozilla Poster. 我正在使用Mozilla Poster测试GET和DELETE。 Should I add a separate socket/port to handle the same? 我应该添加一个单独的套接字/端口来处理吗? Because when I try now, sometimes I get timeout error or no response found. 因为当我现在尝试时,有时会出现超时错误或找不到响应。 However, I am able to see server response in Logcat window. 但是,我能够在Logcat窗口中看到服务器响应。 Please help me. 请帮我。 Code to handle GET request: 处理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);
}
}
The link http://www.integratingstuff.com/2011/10/24/adding-a-webserver-to-an-android-app/ has a very good example. 链接http://www.integratingstuff.com/2011/10/24/adding-a-webserver-to-an-android-app/有一个很好的例子。 I missed conn.close() in my code. 我在代码中错过了conn.close()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.