簡體   English   中英

使用REST處理HTTP獲取/刪除Android

[英]Handling HTTP Get/ Delete Android using REST

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

鏈接http://www.integratingstuff.com/2011/10/24/adding-a-webserver-to-an-android-app/有一個很好的例子。 我在代碼中錯過了conn.close()。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM