Handling HTTP Get/ Delete Android using REST

五迷三道 提交于 2019-12-11 15:39:11

问题


I m implementing a REST based HTTP server in Android. The server responds for GET, DELETE and POST requests. 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).

I m testing the GET and DELETE using Mozilla Poster. 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. Please help me. Code to handle GET request:

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);
       }                    
}   

回答1:


The link http://www.integratingstuff.com/2011/10/24/adding-a-webserver-to-an-android-app/ has a very good example. I missed conn.close() in my code.



来源:https://stackoverflow.com/questions/13816537/handling-http-get-delete-android-using-rest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!