2012-01-10 67 views
1

我需要提供一个REST风格的API,可以在带有CRUD功能的红宝石上开发,适用于Android应用程序。我之前没有与手机操作系统(android/iphone)集成RoR。所以,请帮助我开始。Ruby on Rails中用于Android操作系统的API

在此先感谢。

回答

2

您可以将数据作为Json数据包发送到设备,并在设备中解析json数据包并访问数据。你对web服务的调用应该是一个http调用,例如这是给客户端的。

HTTP:\服务器\方法An Iteraitve \ get_somedata名=东西

和服务器应该在数据库中查询此参数并发送给您的效应初探为JSON?解析json并获取您的详细信息。

String url = "http:\\example.com\mycontroller\get_employee?id=2" 

HttpPost httpPostRequest = new HttpPost(url); 
    StringEntity se; 
    se = new StringEntity(jsonObjSend.toString()); 


    httpPostRequest.setEntity(se); 
    httpPostRequest.setHeader("Authorization", usercredential); 
    httpPostRequest.setHeader("Accept", "application/json"); 
    httpPostRequest.setHeader("Content-type", "application/json"); 

    long t = System.currentTimeMillis(); 
    response = (HttpResponse) httpclient.execute(httpPostRequest); 
    Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]"); 

    HttpEntity entity = response.getEntity(); 

    if (entity != null) { 

     InputStream instream = entity.getContent(); 
     Header contentEncoding = response.getFirstHeader("Content-Encoding"); 
     if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { 
      instream = new GZIPInputStream(instream); 
     } 

     // convert content stream to a String 
     String resultString= convertStreamToString(instream); 
     Log.v(null, "resultString "+resultString); 
     instream.close(); 


     // Transform the String into a JSONObject 
     if(resultString!=null){ 
      jsonObjRecv = new JSONObject(resultString); 

     } 

     // Raw DEBUG output of our received JSON object: 
     Log.i(TAG,"<jsonobject>\n"+jsonObjRecv.toString()+"\n</jsonobject>"); 

     return jsonObjRecv; 

在服务器端,您应该在名为mycontroller的控制器中使用get_employee方法。在该方法可以处理该请求作为一个正常的HTTP请求和发送响应作为JSON例如

employee = Employee.find_by_id(params[:id]) 
    @js_response = ActiveSupport::JSON.encode(employee) 
respond_to do |format| 
    format.json { render :json => @js_response} 
    format.html 
end 

为CRUD需要创建与像delete_employee合适的参数,update_employee等是指json.org来创建不同的方法/解析JSON在Android

+0

嗨@Andro,Thanx的响应,但我应该如何将它与红宝石集成,我需要一个授权系统,将设计与Omniauth工作? – Metal 2012-01-11 05:13:54

+0

我们使用了base64认证。我没有意识到omniauth。抱歉 – AD14 2012-01-11 15:01:28