2013-04-03 6 views
8

üzerinden Ruby on Rails uygulamasına Gönderim Bu yüzden yazıyorum bir Android uygulamasından bir raylar uygulaması yayınlamak çalışıyorum. Raylar uygulamasından başarılı bir şekilde yayınlayabiliyorum. Ayrıca, Simple Rest istemcisi olarak adlandırılan bir chrome eklentisini kullanarak da başarılı bir şekilde yayınlayabildim. android

enter image description here

denemek ve Android'den sonrası onun raylar app isabet ancak boş bir yazı oluşturarak app

. Giriş verilerinin hiçbiri raylar tarafından alınmıyor.

Bu üçüncü parti uygulamaların yalnızca kimlik doğrulamasına bağlı olarak bir Rails uygulamasından GET yapabildiğini okudum. Bu yüzden bunu Rails yapılandırmasına eklediğimde sorun olmadığından emin olmak istiyorum. Sorunum benim Raylar arka uç ya da benim Android müşteri ile yatıyor nerede olarak emin değilim Bu noktada

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

. Ben ulaşmaya çalışıyorum benim denetleyicisi Raylar sonrası yöntemi İşte burada

# 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 

olan Mesaj İsteği göndermek için Android java kodu yani

Tamam. Bu benim

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(); 

      } 

POST çalışıyorum Kullanıcı girişi verilerinde geçen yöntemdir Ve bu HTTP POST permorming, aktarıldığı, bu sınıftır.

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; 

    } 
    } 

Bu

yukarıdaki sınıfta postparams ne için günlüğünün dışarı, yani Günlüğü Kedi sunucusundan yanıt olarak neyi gösterdiğini aslında

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

budur gönderilen verileri biliyoruz

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"} 

Gerçekten sorunun nerede yattığını anlamak için oldukça uğraşıyorum ve bir süreliğine üzerine takıldım. Herhangi bir anlayış çok takdir edilecektir. Ve daha fazla bilgi gerekirse sadece bağırmak.

Düzenleme:

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) 

Bu

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

Yapmak yayında parametre listesi dökümü için hızlı bir php script yazabilir miyim emin orada oluyor? $ _POST dizisini bir dosyaya atın ve inceleyin. – Dave

+0

Bunu daha çok düşündüm. Bir listeyi hiç göndermedim ve JSON içeriği olduğunu söyledim, her zaman JSONObject'i oluşturdum ve daha sonra isim/değer çifti query = jsonobject gönderdim, sonra sunucumda sorgu değerini json dizesi olarak aldım. – Dave

+0

Sadece Rest İstemciden bir istekte bulunacağım ve compharion için oradaki uygulamamdan, – DavedCusack

cevap

6

JSON, standart POST URL kodlanmış parametreler gönderiyorsunuz.

Aslında bir JSON nesnesi göndermek gerekir

:

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

Sorunun içindeki kod param postInformationtoAPI() yöntemi? Düzenleme: Bu arada yardım için teşekkürler Teşekkürler – DavedCusack

+1

Cody çok teşekkür ederim bana çok fazla kalp ağrısı kaydettirdi. JSON nesnesini geçirerek ve bunu varlığa ekleyerek "entity.setContentType (" application/json; charset = UTF-8 ");" Sunucuya gönderebildim – DavedCusack

1

sorunu gönderme android uygulamasından olduğunu Bu basit DİNLENME istemciden başarılı bir yayın sunucudan

gelen günlükleri edildiğinde sizi o Android'de POST'u yeniden oluşturuyorsanız, nesneyi (vücut) fazla yazıyorsunuz. İlk başta ayarladınız ve daha sonra yeniden ayarladığınız şeyi etkin bir şekilde temizliyorsunuz.

httpPost.setEntity(new UrlEncodedFormEntity(postparams)); 

Ama sonra birkaç satır daha sonra bunu aşırı yazma:

Bu doğrudur Böylece 2 setEntity() çağrıyı hendek

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

.

Yapman çalıştığınız şeyi elde edebilirsiniz - gibi kodunuzu değişiklikler yaparak UTF-8 POST gövdesini ayarı: JSON bir içerik türünü ayarlayarak ama aslında göndermiyoruz

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

Yanıt için teşekkürler Cody, ne demek istediğini anlıyorum ve şimdi uygulama yapmaya çalışacağım – DavedCusack

+0

sunucusu. Yanlış da başka bir şey yapmalıyım. – DavedCusack

+0

ile çalışmadığımı yansıtmak için sorudaki kodu güncelleyeceğim * Şu anda çalıştığım şeyi yansıtmak için sorudaki kodu güncelleyeceğim – DavedCusack