2012-12-11 12 views
0

我在Android中實現基於REST的HTTP服務器。服務器響應GET,DELETE和POST請求。兩個Android設備使用HTTP Post進行通信(我使用的是服務,其中設備一直在監聽端口併發布到下一個設備,並繼續進行)。處理HTTP使用REST獲取/刪除Android

我使用Mozilla海報測試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); 
     }      
} 
+2

從您的服務器處理程序發佈一些代碼 – njzk2

+0

編輯我的問題@ njzk2 – user1741274

+0

這就是得到的,對嗎?你介意縮小一點嗎?你已經有DELETE的東西了嗎? – njzk2

回答