Recently wanted to get an Android app that has access to the Internet, because it's fast so it uses Ruby on Rails to provide HTTP resources. This information is still relatively small, so the attempt to record the process.
1 building Web application with Ruby on Rails
1.1 New Web Application
CD Test
1.2 Generate product
Rails Generate Scaffold Product reference:string quantity:decimal
Rake Db:migrate
Start the service
Rails Server
Open Http://localhost:3000/products
You should see the following information (this is the result of get, but it is not yet recorded):
Add a record to the Web page, click "New Product", go to "http://localhost:3000/products/new", fill in the information and click "Greate Product" (this commits a post):
In other words, both get and POST on the web side can be executed.
1.3 Using JSON format to transfer data first try GET JSON format data
Open: Http://localhost:3000/products/1.json
As you can see, using Ruby on Rails is a straightforward means of getting Json data, which is why?
To figure out how the Json data came in, check out the routes
Rake routes
The following results are displayed:
So the input http://localhost:3000/products/1.json corresponding to the Controller inside the show, in the code to find show (test/app/controllers/products_ CONTROLLER.RB):
Hey! What's the situation? Can you support Json directly without writing anything? That's too cool.
Try the Post Json-formatted data again
As already known, with the Web page can submit a post, first trace the next post, using the Developer tool to view the Web page submitted when the submission of a post:
This POST is based on the previous Routes should be given to the controller in create.
So it is @product = Product.new (product_params) to create the object @product. Save Object. So, how did Product_params get here?
All right, here's the thing.
Well.. Still did not solve I want the Json transfer method, and then search for the big god ...
Add the following code to the TEST/APP/CONTROLLERS/PRODUCTS_CONTROLLER.RB to accept the Json data submitted by the Android app.
def Create_from_app Data_json=json.parse request.body.read = product.new (data_json) @product. Save End
1.4 Test if GET and POST are normal
The test uses Firefox's Poster tool.
Test GET
Test POST
Make up an episode: There was an error when submitting the POST directly:
Paste the contents of the error into HTML and find the error:
Baidu asks the big God to get this answer:
This is a new feature, starting with Rails 2.0, designed to prevent CSRF (Cross-site Request forgery) from attacking
There are several ways to solve this problem
Please forgive me for being directly violent. Choose the way to disable CSRF, find test/app/controllers/products_controller.rb, insert code
Protect_from_forgery:except = : Index # can disable CSRF protection on Controller-by-controller basis: Skip_before_filter:verify_authenticity_token
Restart Rails Server
Problem resolution, submit the POST again:
This means that the Android client can only send HTTP requests in the format above.
2 using an Android client to access HTTP resources
2.1 Getting permission to access the network
Add the following line to the Androidmanifest.xml file
<android:name= "Android.permission.INTERNET"/>
2.2 Submitting a GET request using the Android client
Try { FinalString url = "http://192.168.0.138:3000/products/" +message+ ". JSON"; Thread Thread=NewThread (NewRunnable () {@Override Public voidrun () {Try{httpget HttpGet=Newhttpget (URL); HttpResponse HttpResponse=Newdefaulthttpclient (). 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 Submitting a POST request using an Android client
Try{Thread Threadpost=NewThread (NewRunnable () {@Override Public voidrun () {Try { FinalString url = "Http://192.168.0.138:3000/products"; HttpPost HttpPost=Newhttppost (URL); Jsonobject JSON=NewJsonobject (); Json.accumulate ("Reference", "888"); Json.accumulate ("Quantity", "8"); Jsonobject Response=NULL; stringentity s=Newstringentity (json.tostring ()); S.setcontentencoding ("UTF-8"); S.setcontenttype ("Application/json"); Httppost.setentity (s); HttpResponse HttpResponse=Newdefaulthttpclient (). 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 (); }