Metal
Metal

Reputation: 205

API for Android OS in ruby on rails

I need to provide an RESTful api to be developed in ruby on rails with CRUD features for an android app. I haven't worked with mobile phone OS(android/iphone) integration with RoR earlier. So, please help me getting started.

Thanks in advance.

Upvotes: 1

Views: 2795

Answers (1)

AD14
AD14

Reputation: 1218

you can send the data as Json packets to the device and in device parse the json packets and access the data. your calls to webservice should be a http call eg this is for the client.

http:\server\metnod\get_somedata?name=something

and the server should query the database for this parameter and send you the reponse as Json. parse json and get your details.

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;

In the server side you should have a get_employee method in a controller called mycontroller. in the method you can process the request as a normal http request and send the response as json eg

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

for CRUD you need to create different methods with appropriate parameters like delete_employee, update_employee etc. refer json.org to create/parse json in android

Upvotes: 2

Related Questions