使用 Android 用戶端向 Ruby on rails 構建的 Web Application 提交 HTTP GET 和 HTTP POST 請求

來源:互聯網
上載者:User

標籤:des   android   cWeb   style   class   blog   

最近想弄個能訪問 Internet 的 Android 應用,因為求快所以用了 Ruby on Rails 來提供 HTTP 資源。這方面的資料還是比較少的,所以把嘗試的過程記錄下來。

 

1 使用 Ruby on Rails 構建 Web Application

 

1.1 建立 Web Application
rails new Test 
cd Test
1.2 產生 product
rails generate scaffold product reference:string quantity:decimal
rake db:migrate

 啟動服務

rails server

 開啟http://localhost:3000/products

 應該可以看到以下資訊(這個就是GET的結果啦,只不過現在還沒有記錄):

 在網頁上添加一條記錄,單擊“New Product”,會轉到“http://localhost:3000/products/new”,在裡面填寫資訊後單擊“Greate Product”(這樣就提交了一個 POST):

也就是說,網頁端的 GET 和 POST 都是可以執行的。

 

1.3 使用 Json 格式傳輸資料先試試 GET Json 格式的資料

開啟:http://localhost:3000/products/1.json

可以看到,使用 ruby on rails 是可以直接獲得 Json 資料的,這是為什麼呢?

為了弄清楚 Json 資料是怎麼來的,先查看 routes

rake routes

顯示出以下結果:

所以輸入的 http://localhost:3000/products/1.json 對應的是 Controller 裡面的 show,在代碼裡找到show(Test/app/controllers/products_controller.rb):

咦!什麼情況?啥都不寫就能直接支援 Json ?這也太牛逼了吧。

 

再試試 Post Json 格式的資料

前面已經知道,用網頁可以提交一個 POST,先跟蹤一下下這個 POST,用開發人員工具查看網路知道頁面提交的時候提交了一個 POST:

這個 POST 根據前面的 Routes 應該是給了 controller 裡的 create。

所以是 @product = Product.new(product_params) 建立對象,@product.save 儲存對象。。那麼 product_params 怎麼來的呢?

好吧,是這樣來的。。。

 

嗯。。還是沒有解決我想要的 Json 傳輸方法,後來還是搜尋找大神。。。

在 Test/app/controllers/products_controller.rb 中添加以下代碼,用於接受 Android App 提交的 Json 資料。

  def create_from_app      data_json=JSON.parse request.body.read      @product = Product.new(data_json)      @product.save  end

 

1.4 測試 GET 和 POST 是否正常

測試使用的是Firefox的 Poster 工具。

測試 GET

測試 POST

補上一段小插曲:直接提交 POST 時是出錯的:

把出錯的內容粘貼出來存成html,發現是這個錯誤:

百度求大神,得到這樣的答案:

這是從rails 2.0 開始包含的一個新功能,目的在於防止CSRF(Cross-Site Request Forgery)攻擊

有這樣幾種解決方式

請原諒我直接暴力地選擇了禁用 CSRF 的方式,找到Test/app/controllers/products_controller.rb,插入代碼

  protect_from_forgery :except => :index      # you can disable csrf protection on controller-by-controller basis:    skip_before_filter :verify_authenticity_token  

重啟 rails server

問題解決,再次提交 POST:

也就是說 Android 用戶端只要能按照以上格式發送 HTTP 要求就可以了。

 

 

2 使用 Android 用戶端訪問 HTTP 資源

 

2.1 擷取訪問網路的許可權

在 AndroidManifest.xml 檔案中添加以下行

<uses-permission android:name="android.permission.INTERNET"/>

 

2.2 使用 Android 用戶端提交 GET 請求
        try {            final String url = "http://192.168.0.138:3000/products/" + message                    + ".json";            Thread thread = new Thread(new Runnable() {                @Override                public void run() {                    try {                        HttpGet httpGet = new HttpGet(url);                        HttpResponse httpResponse = new DefaultHttpClient()                                .execute(httpGet);                        if (httpResponse.getStatusLine().getStatusCode() == 200) {                            result = EntityUtils.toString(httpResponse                                    .getEntity());                        }                    } catch (Exception e) {                        e.printStackTrace();                    }                }            });            thread.start();            thread.join();        } catch (InterruptedException e) {            e.printStackTrace();        }

 

2.3 使用 Android 用戶端提交 POST 請求
try{        Thread threadPost = new Thread(new Runnable() {            @Override            public void run() {                try {                    final String url = "http://192.168.0.138:3000/products";                    HttpPost httpPost = new HttpPost(url);                                        JSONObject json = new JSONObject();                    json.accumulate("reference", "888");                    json.accumulate("quantity", "8");                    JSONObject response = null;                    StringEntity s = new StringEntity(json.toString());                    s.setContentEncoding("UTF-8");                    s.setContentType("application/json");                    httpPost.setEntity(s);                                        HttpResponse httpResponse = new DefaultHttpClient()                            .execute(httpPost);                    if (httpResponse.getStatusLine().getStatusCode() == 200) {                        result = EntityUtils.toString(httpResponse.getEntity());                    }                } catch (Exception e) {                    e.printStackTrace();                }            }        });        threadPost.start();        threadPost.join();        } catch (Exception e) {            e.printStackTrace();        }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.