RESTful RAILS and Android HttpRequests - android

I am currently working on building an Android app for my Rails backend.
I created api_tokens_controller to create an api_token when user logs in from Android using HttpPost and save that token both in Rails user table and Android shared preferences. I was able to verify this.
I am trying to send the api_token as params[:api_token] from my Android app with every subsequent request after initial log in and have Rails verify:
In User.rb:
def self.authenticate_with_api_token(api_token_from_mobile)
user = find_by_api_token(api_token_from_mobile)
if user.nil?
return nil
else
return user
end
end
if user exists, then send other data as JSONObjects.
I am running into trouble conceptually here. I am now trying to have the Android app go to
...:3000/users and HttpGet user data as JSONObjects. The problem is that I don't know how to send the api_token from Android app to Rails in HttpGet. I am assuming that since it is RESTful, my HttpRequests have to correspond to the way rails routes work.
Questions:
Is it possible to send in JSONObject of params[:api_token] from android app to Rails in HttpGet?
Do my HttpRequests have to correspond to the RESTful way Rails works or can I just only use HttpPost?
Thanks

If I understand you correctly, then you just want to add the API token to as a URL parameter if using GET, so something like:
...:3000/users.json?api_token=token
This will put the api_token in the params hash just the same as POST data would be. The RESTful way would be to use GET for retrieving data from the API and using POST to send data, i.e. changing data on your backend but if you are going to be returning a user with the request then GET is the correct method to be using anyway.

I'm a former Ruby on Rails developer myself.
I agree with Tom that you can just pass in the api_token as a parameter with an HTTP GET.
For your second question, I'd say that the RESTful way is to use all the HTTP Verbs for the different actions that you can take in the API. You could change your routes to use HTTP POST and then supply extra parameters to differentiate between say Create and Update (to emulate a PUT). However, I don't think that's the way forward.
However, the good news is that whether you use HttpClient or HttpUrlConnection in your Android app, you will have access to the different HTTP verbs you need. For HttpClient, it is actually different classes like HttpGet, HttpPost, HttpPut and HttpDelete which you then configure by supplying URL and other parameters. For HttpUrlConnection, you just call it like so:
setRequestMethod("PUT");
Here's the relevant documentation on HttpUrlConnection:
HttpURLConnection uses the GET method by default. It will use POST if setDoOutput(true) has been called. Other HTTP methods (OPTIONS, HEAD, PUT, DELETE and TRACE) can be used with setRequestMethod(String).

Related

Pass parameters Using HTTP request

Hi i am new to android programming and i would like to know how to call a web service and pass parameters to the web service to obtain the return result in form of an XML.
I previously used Ksoap lib and SOAP request but thats not working correct so now i am trying the HTTP method.
Please Help
You will want to read up on the Apache HttpClient.
Beyond that its a matter of making sure the device and server are generating messages that the other side can correctly parse.
Is the server an existing service? Or are you designing that as well?
check the following in which you will use HTTP post request & you will get response in the form on XML
Android HttpPost: how to get the result

How to perform client-server communication with android app? Can I use servlet on server side or do I need to implement web service?

I am developing an android app where a user has to enter his login details for authentication...the app will then check username and password entered by user on server and will act accordingly..so how to pass these login details to server..and do I need to implement web service on server side or can use servlet?
Can anyone please tell me which Web Service should I use for the above purpose...also I need to send other data from my client app to server, process it on server and give back the reply to client app...also how to implement a web service? Are there any tools for it? Any tutorials would be of great help.
Thanks in advance...
well, to send data to the server you can use HttpPost and HttpGet requests.
and as you need to get results from the server then, yes you'll need a web service.
You can use servlet (or) webservice, any service, as long as it can be accessed through URL. Make sure the servlet/webservice returning XML/JSON (one of these two formats are preferred, you need to code your servlet/service to return response in one of these formats) response when you hit the URL in internet explore. Once you make sure URL is returning data, then
1) In your app, using HTTPClient, invoke the URL
2) You will get either XML/JSON
3) If it JSON, use in buit JSONObject to parse the response and get the data
If response is XML, use either SAX/Dom parsing to parse the response.

Android App Development and Web Server Interactions

I am just learning about Android Development so excuse me if this is a bit off in nature.
I am wanting to make an app that interacts with a Database from my website, in a sense the two things will be one feeding the other. So with that. I am trying to figure out whats the best way to interact with my server. I don't want an app thats an app in a browser like environment I want to dev a full app that works independently of the site only sharing the DB and like features. So what would be my best approach?
Is building the app so it can post/get to php files on the server interacting basically through JSON/XML my best and or safest bet or is there a better approach that connects the App to the servers Database that doesn't require me to open the database to any ip that makes a request.
Just looking for opinions and suggestions here. I figure everyone who's going to see this is familiar with Android development and best practices where as I could and have surfed blogs and all else but the opinion seems to be 50/50 as to which is best.
I'm sure there are libraries out there for Android that help you with HTTP Get and Post, however, if you really want to understand what is going there are just a couple of classes you have to understand in order to make the necessary classes yourself.
First, get to know HttpClient, HTTPGet, HTTPPost, and HTTPResponse. Some of the later versions of Android have some nice other classes as well, but those four is pretty much all you need to get started.
You need to do something like this:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://www.myurl.com/api_name");
HttpResponse response = client.execute(request);
If you debug this (with a real URL of course), you'll notice that your app kind of freezes during client.execute(). This is the point at which the request has actually fired and the app is waiting for a response. Once you actually get the response, it isn't very difficult to get the data out of it.
Once you understand this, you'll want to get to know AsyncTask, which is endlessly useful for performing background tasks. You can find the documentation here: http://developer.android.com/reference/android/os/AsyncTask.html There is a great example of how to use this right at the top.
Using these two concepts together you can perform asynchronous HTTP requests. Basically, put your actual HTTP execute code in doInBackground of your AsyncTask. At the end of the doInBackground return your response, and then do what you want with your data in the AsyncTask's onPostExecute.
We've found that providing a proper RESTful web API that hits the database on the backend in whatever language you choose (be it PHP, RoR, whatever) provides a useful interface for any number of uses (your own website, mobile apps, etc).
Then it's a matter of your Android app interacting with the RESTful API, which is simply HTTP requests. Those can be encapsulated in helper classes to make them straightforward as well.
Based on my experience, the best framework for doing RESTFul things with Android is: Spring Android
From a client perspective, it provides all the tools needed to access secure RESTFul services. Since it is Spring, it provides nice abstractions over most of the boiler plate http code. As an example, it provides a clean way to perform a GET that returns json, and then serialize that to a POJO.
As an example:
RestTemplate restTemplate = new RestTemplate();
// Add Jackson JSON Message Converter to Template
restTemplate.setMessageConverters(
new ArrayList<HttpMessageConverter<?>>() {
{
add(new MappingJacksonHttpMessageConverter());
}
}
);
// Simple Conversion - pojo is now populated
MyPojo pojo = restTemplate.getForObject(url, MyPojo.class);
The approach you mention in the question: PHP on the server and JSON for requests/responses, does work. But getting it perfect can be tricky.
I found it helpful to have small request/reponse classes for each call on the Android side, like SaveNoteToServerRequest, SaveNoteToServerResponse classes which are just plain java objects with whatever fields are needed for the request/response. Then you can use a library like GSON to convert the request object to JSON and convert the http response from JSON to the response object.
On the PHP side you can create a small class for the response object, then json_encode at the end.
That way you're not directly manipulating JSON objects, just using your own plain java objects or php classes most of the time.
Hope that helps.

Android web app

What are the best ways to connect site and show it's data on an android application ? Also does I have to create anything on server where the site is for using JSON ? I am new to programming web android application's, though I searched a lot I didn't find anything which would explain me straight to the point.
You're on the solid ground starting out using JSON as the interchange between the two.
Alot of popular mobile apps like Twitter and Foursquare have restful APIs set up to interact with their mobile clients by exchanging HTTP requests that contain data formatted as JSON. Most of the communication between the two can be accomplished with HTTP requests using the standard GET and POST methods.
A good place to start would be setting up some server endpoints that output this data and then setting up your android app to request and parse this data just like a browser would. You just need to set the appropriate mimetypes on your server end (application/json).
Most modern server-side languages have implemented modules/functions that can take their native data structures and approximate them in serialized JSON (PHP's json_encode(), python's json.dumps() etc) These can be used to output data from within the app or database to your mobile client where it can be interpreted and used in the Java environment there.
To pass back JSON you need to set the mime type (http://stackoverflow.com/questions/477816/the-right-json-content-type), which is application/json.
If you are passing back JSON or XML then the client just needs to make the appropriate http call, most likely GET, perhaps POST, to actually retrieve the information.
You can use something like this as a starting point:
http://lukencode.com/2010/04/27/calling-web-services-in-android-using-httpclient/

Android web server authentication with JsonRPC

I've been doing some research and it seems my best option to go with an Android-Client/PHP-Server application is by using JsonRPC. My question is, How would an authentication mechanism work?
I'd use Zend for json server and Android-json-rpc as client. Or is there a better way to do a remote authentication?
If you want to do a simple API key then in every JSON call, the client would pass the auth key and in each method on the php side would get the key and authenticate it.
If you wanted to do session type authentication, you would have to first call an authenticate method that would return the session_id to the client. The client would then send the session key in every subsequent method. Within the methods, the server could then check the session key.
I have looked for a way to cleanly abstract authentication out of the actual json RPC methods, but if you use Zend_Json_Server directly, there is no way to do it. You may be able to extend it, but to me, it wasn't worth the hassle.
just like browser works . Browser also sends session id in every request using cookies . You can build the similar functionality with your java REST client by appending that id to every request .Then in php code you can do
session_id($_GET('session_id'));
session_start();
your rest client will send this session_id in every request to be identified. This way you can use php sessions just like with browsers.

Categories

Resources