2013-04-03 21 views
8

Così sto provando a postare su un'app per rails da un'app per Android che sto scrivendo. Sono in grado di postare con successo dall'interno dell'app rails. Sono stato anche in grado di pubblicare con successo usando un add-on chrome chiamato Simple Rest client.Pubblicazione sull'app Ruby on Rails da Android

enter image description here

Quando provo e post dal suo app Android che colpisce l'applicazione rotaie ma la creazione di un posto vuoto. Nessuno dei dati di input viene ricevuto dalle guide.

Ho letto che le applicazioni di terze parti sono in grado di ottenere da un'app Rails solo in base all'autenticazione, in modo da assicurarsi che questo non fosse il problema che stavo avendo aggiunto alla mia configurazione di Rails.

# de-activate tolken auth 
config.action_controller.allow_forgery_protection = false 

A questo punto non sono sicuro da dove il mio problema si trova, con il mio Rails backend o il mio cliente Android.

ok così il metodo post Rails nel mio controller che sto cercando di raggiungere è qui

# POST /orders 
    # POST /orders.json 
    def create 
    @order = Order.new(params[:order]) 

    respond_to do |format| 
     if @order.save 
     format.html { redirect_to @order, notice: 'Order was successfully created.' } 
     format.json { render json: @order, status: :created, location: @order } 
     else 
     format.html { render action: "new" } 
     format.json { render json: @order.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

Ecco il codice Java di Android per l'invio del messaggio Request. questo è il metodo che passa i dati di input dell'utente che sto cercando di POST

private void postInformationtoAPI() { 

       showToast("POSTING ORDER"); 
       List<NameValuePair> apiParams = new ArrayList<NameValuePair>(); 
       apiParams.add(new BasicNameValuePair("drinks_id", GlobalDrinkSelected)); 
       apiParams.add(new BasicNameValuePair("name", GlobalEditTextInputName)); 
       apiParams.add(new BasicNameValuePair("paid" , GlobalIsPaid)); 

       bgtPost = new BackGroundTaskPost(MAP_API_URL_POST_ORDER, "POST", apiParams); 
       bgtPost.execute(); 

       goToOrderCompleted(); 

      } 

e questa è la classe che è passato a, permorming HTTP POST.

public class BackGroundTaskPost extends AsyncTask<String, String, JSONObject> { 

    List<NameValuePair> postparams = new ArrayList<NameValuePair>(); 
    String URL = null; 
    String method = null; 

    static InputStream is = null; 
    static JSONObject jObj = null; 
    static String json = ""; 

    public BackGroundTaskPost(String url, String method, List<NameValuePair> params) { 
     this.URL = url; 
     this.postparams = params; 
     this.method = method; 

     for (int i = 0; i < postparams.size(); i++){ 
      String test = postparams.get(i).toString(); 
      Log.d("This is in the lisht:", test); 
     } 
    } 

    @Override 
    protected JSONObject doInBackground(String... params) { 
     // TODO Auto-generated method stub 
     // Making HTTP request 
     try { 
     // Making HTTP request 
     // check for request method 

     if (method.equals("POST")) { 
     // request method is POST 
     // defaultHttpClient 

      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(URL); 
      httpPost.setEntity(new UrlEncodedFormEntity(postparams, HTTP.UTF_8)); 
      Log.i("postparams : ", postparams.toString()); 
      httpPost.setHeader("Content-Type", "application/json"); 
      httpPost.setHeader("Accept", "application/json"); 

      HttpResponse httpResponse = httpClient.execute(httpPost); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      is = httpEntity.getContent(); 

     } else if (method == "GET") { 
     // request method is GET 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     String paramString = URLEncodedUtils 
      .format(postparams, "utf-8"); 
     URL += "?" + paramString; 
     HttpGet httpGet = new HttpGet(URL); 

     HttpResponse httpResponse = httpClient.execute(httpGet); 
     HttpEntity httpEntity = httpResponse.getEntity(); 
     is = httpEntity.getContent(); 
     } 

     } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
     } catch (IOException e) { 
     e.printStackTrace(); 
     } 

     try { 
      Log.i("Logging out *is* before beffered reader", is.toString()); 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
     is, "utf-8"), 8); 
     Log.i("Logging out *is* after beffered reader", is.toString()); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
     sb.append(line + "\n"); 
     } 
     is.close(); 
     json = sb.toString(); 
     Log.i("json: ",json); 
     } catch (Exception e) { 
     Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } 

     // try parse the string to a JSON object 
     try { 
     jObj = new JSONObject(json); 
     } catch (JSONException e) { 
     Log.e("JSON Parser", "Error parsing data TEST " + e.toString()); 
     } 

     // return JSON String 
     return jObj; 

    } 
    } 

Questa è la cosa del registro per postparams nella classe di cui sopra, quindi so di dati viene effettivamente inviati

04-03 21:36:23.994: I/postparams :(690): [drinks_id=41, name=Dave, paid=True] 

Questo è quello che Log gatto sta mostrando come una risposta dal server

04-03 20:56:08.247: I/json:(690): {"created_at":"2013-04-03T20:56:06Z","drinks_id":null,"id":1351,"name":null,"paid":null,"served":null,"updated_at":"2013-04-03T20:56:06Z"} 

Sto davvero lottando per capire dove si trova il problema e ci siamo bloccati per un bel po '. Qualsiasi intuizione sarebbe molto apprezzata. E se sono necessarie ulteriori informazioni basta gridare.

Edit: tronchi da server

Questo è un post di successo dal semplice client REST

2013-04-03T23:13:31+00:00 app[web.1]: Completed 200 OK in 15ms (Views: 8.7ms | ActiveRecord: 5.2ms) 
2013-04-03T23:13:42+00:00 app[web.1]: Started POST "/orders.json" for 89.101.112.167 at 2013-04-03 23:13:42 +0000 
2013-04-03T23:13:42+00:00 app[web.1]: Processing by OrdersController#create as JSON 
2013-04-03T23:13:42+00:00 app[web.1]: Parameters: {"updated_at"=>nil, "drinks_id"=>51, "id"=>1021, "name"=>"Test", "paid"=>true, "served"=>nil, "created_at"=>nil, "order"=>{"drinks_id"=>51, "name"=>"Test", "paid"=>true, "served"=>nil}} 
2013-04-03T23:13:43+00:00 heroku[router]: at=info method=POST path=/orders.json host=fyp-coffeeshop.herokuapp.com fwd="89.101.112.167" dyno=web.1 connect=1ms service=25ms status=201 bytes=138 
2013-04-03T23:13:43+00:00 app[web.1]: Completed 201 Created in 15ms (Views: 0.6ms | ActiveRecord: 13.2ms) 

Questo è dalla applicazione android distacco

2013-04-03T22:56:45+00:00 app[web.1]: Started POST "/orders.json" for 89.101.112.167 at 2013-04-03 22:56:45 +0000 
2013-04-03T22:56:45+00:00 app[web.1]: Processing by OrdersController#create as JSON 
2013-04-03T22:56:45+00:00 app[web.1]: Completed 201 Created in 23ms (Views: 2.2ms | ActiveRecord: 16.3ms) 
2013-04-03T22:56:45+00:00 heroku[router]: at=info method=POST path=/orders.json host=fyp-coffeeshop.herokuapp.com fwd="89.101.112.167" dyno=web.1 connect=4ms service=37ms status=201 bytes=138 
+0

si può scrivere uno script PHP rapido per scaricare l'elenco dei parametri nel post per assicurarsi che si sta facendo lì? Lancia l'array $ _POST in un file ed esaminalo. – Dave

+0

Stavo proprio pensando a questo di più. Non ho mai inviato un elenco e ho detto che era contenuto JSON, ho sempre creato il JSONObject, quindi ho postato il nome/valore coppia query = jsonobject, quindi sul mio server il valore della query è stato preso come stringa json. – Dave

+0

Ho appena disconnesso una richiesta dal client Rest e dalla mia app lì per il comparsion, aggiornerò la mia domanda – DavedCusack

risposta

6

Si sta impostando un tipo di contenuto di JSON, ma in realtà non l'invio JSON, stai inviando parametri codificati con url POST standard.

È necessario inviare in realtà un oggetto JSON:

JSONObject params = new JSONObject(); 
params.put("drinks_id", GlobalDrinkSelected); 
params.put("name", GlobalEditTextInputName); 
params.put("paid", GlobalIsPaid); 

StringEntity entity = new StringEntity(params.toString()); 
httpPost.setEntity(entity); 
+0

Il codice nella mia domanda non aggiunge i parametri in il metodo postInformationtoAPI()? Modifica: grazie per l'aiuto dal modo in cui – DavedCusack

+1

Cody grazie mille mi hai salvato un sacco di mal di cuore. Passando nell'oggetto JSON e aggiungendolo all'entità "entity.setContentType (" application/json; charset = UTF-8 ");" Sono stato in grado di postare sul server – DavedCusack

1

Il problema è che quando si Stai costruendo il POST in Android stai sovrascrivendo l'entità (il corpo). Inizialmente lo hai impostato e quindi lo hai impostato nuovamente, eliminando in modo efficace ciò che hai già impostato.

Questo è corretto:

httpPost.setEntity(new UrlEncodedFormEntity(postparams)); 

Ma poi un paio di righe dopo si over-scrivere con:

httpPost.setEntity(new StringEntity("UTF-8")); 

Così fosso che secondo setEntity() chiamata.

È possibile ottenere ciò che si sta cercando di fare - l'impostazione del corpo POST in UTF-8 per ottimizzare il codice come:

httpPost.setEntity(new UrlEncodedFormEntity(postparams, HTTP.UTF_8)); 
+0

Grazie per la risposta Cody, capisco cosa intendi e proverò ad implementarlo ora – DavedCusack

+0

Mentre sono sicuro che la correzione dell'entità non stia aiutando, I parametri non stanno ancora raggiungendo il server. Devo fare anche qualcos'altro in modo errato. Aggiornerò il codice nella domanda per riflettere ciò che non sto lavorando con – DavedCusack

+0

* aggiornerò il codice nella domanda per riflettere ciò che sto attualmente lavorando con – DavedCusack