我需要提供一个宁静的API,以在Ruby上的Rauds上开发具有CRUD功能的Android应用程序。我没有早些时候与ROR的手机OS(Android/iPhone)集成。因此,请帮助我入门。

提前致谢。

有帮助吗?

解决方案

您可以将数据作为JSON数据包发送到设备,并在设备解析JSON数据包中访问数据。您对Web服务的呼叫应该是HTTP调用,例如适合客户。

http: server metnod get_somedata?name =某物

服务器应查询数据库中的此参数,并将依据发送为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 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

对于CRUD,您需要使用适当的参数创建不同的方法,例如Delete_employee,Update_employee等

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top