繁体   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