Frage

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);
       }                    
}   
War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top