API per Android OS in Ruby on Rails
-
25-10-2019 - |
Domanda
ho bisogno di fornire un'API RESTful da sviluppare in Ruby on Rails con CRUD dispone di un'applicazione Android. Non ho lavorato con il telefono sistema operativo mobile (Android / iPhone) l'integrazione con RoR in precedenza. Quindi, per favore aiutami iniziare.
Grazie in anticipo.
Soluzione
è possibile inviare i dati come JSON pacchetti al dispositivo e in un dispositivo di analizzare i pacchetti JSON e accedere ai dati. le chiamate a webservice dovrebbe essere un http chiamata ad esempio questo è per il cliente.
http:? \ Server \ metnod \ get_somedata name = qualcosa
e il server dovrebbe interrogare il database per questo parametro e ti invieremo la reponse come JSON. parse JSON e ottenere i dati.
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;
Nel lato server che si dovrebbe avere un metodo get_employee in un controller chiamato MyController. nel metodo è possibile elaborare la richiesta come una normale richiesta HTTP e inviare la risposta, come ad esempio 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
per CRUD è necessario creare metodi diversi con parametri appropriati come delete_employee, update_employee ecc riferiscono json.org per creare / parse json in Android