I've a application deployed on google app-engine..it has a registration form.
now i've made a registration form in my android application and i want that on click submit...it should be sent to the application on google app-engine and it should be persisted in the particular db...
somebody told me to use http request and response method but i'm not aware of that thing..
can somebody please provide me with some sample code or something.....
thanksss....
You haven't specified if you're using Python or Java.
You have to decide how you want to connect. At the simplest level you could just POST the data to Google App Engine. In Java you would write a servlet which handles this. See Java EE tutorial. Alternatively you could write a web service (SOAP, RESTful) on the server which handles the data being sent from your application. Again Google this and there are countless examples.
Assume we're going down the simplest POST route. So in your servlet (running on GAE) you'd have something like this:
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String value1 = request.getParameter("value1");
}
And in your android app you'd do something like:
DefaultHttpClient hc=new DefaultHttpClient();
ResponseHandler <String> res=new BasicResponseHandler();
HttpPost postMethod=new HttpPost("http://mywebsite.com/mappedurl");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("value1", "Value my user entered"));
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
String response=hc.execute(postMethod,res);
Of course value1 in the servlet would be set to "Value my user entered".
EDIT: Google have now released their Google Cloud Endpoints - this makes building RESTful services on App Engine and creating clients for Android a lot easier. It does tie you in to App Engine even more though - but certainly worthy of consideration.
Related
I know there are plenty of resources like this on the web, and the closest I've come was the answer to this question: ASP.NET Web API Authentication.
Basically, this is my requirement. Log in via android to my account on an MVC4 internet application I created (which uses SimpleMembership). It is NOT an MVC Web Api app, which seems to confuse things when looking at the various ways of achieving this.
I am attempting to use FormsAuthentication to set an authentication cookie, but I have no idea how to configure my android httpclient to actually send through this authentication cookie, or how to get MVC to save a session from my android app.
So far, this is what I've come up with on the MVC side:
[HttpPost]
[AllowAnonymous]
public bool LoginMobi(LoginModel model)
{
var membership = (SimpleMembershipProvider)Membership.Provider;
if (membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, false);
return true;
}
else return false;
}
And I use the following java in my android app (sent over an SSL connection):
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://mysite/api/login");
List<NameValuePair> nameValue = new ArrayList<NameValuePair>();
nameValue.add(new BasicNameValuePair("UserName", "foo"));
nameValue.add(new BasicNameValuePair("Password", "bar"));
httppost.setEntity(new UrlEncodedFormEntity(nameValue));
httppost.setHeader("Content-type", "application/json");
HttpResponse response = httpclient.execute(httppost);
// etc etc
What I haven't figured out is how to receive the authentication cookie on android and send it back with each request to controllers with the [Authorize] attribute. I'm rather new to this so please forgive my ignorance!
You are using FormsAuthentication which uses cookie to identify user for each request. You have two options here.
Use CookieStore for HttpClient. Check Android HttpClient and Cookies
OR
Combine BASIC auth and FormsAuthentication. Check Combining Forms Authentication and Basic Authentication
Hope this helps.
As of now, if I have to store something from Android to the server, I make an HTTP request of a GET URL, with data in the form of parameter values. On the server side, I use PHP to extract the parameter values and store them in database.
Similarly, if I want to get something from the server to Android, I post a JSON string on the webpage using PHP. Then I read it in Android using HTTP request, convert the string to JSON and then use the data.
This method of PHP-MySQL-Android-JSON is very easy but not secure. Suppose I want to store the score of player from my game in Android to the server's database, it is easy to execute some URL like www.example.com/save_score.php?player_id=123&score=999 from Android. But anyone can update his score if he comes to know the php file name and names of parameters, by simply typing this URL in a browser.
So what is the correct method of interacting with a server (my server supports PHP but not Java)?
I have heard about RESTful and KSOAP2, but know nothing about them. Can you please explain them a bit in lay man language (reading the proper definitions didn't help me)? What are these used for?
What is the best way to send score to the server? Any tutorial link would be great.
Thanks.
Edit 1:
I don't use proguard to obfuscate my code for several reasons. So anyone can reverse engineer the apk, look into the code, find the URL to update the score, write his own POST method and update his score. How can I stop this from happening?
Use POST method to post data from android and get it in php. e.g. use this method to send your data in json formate , which will not be showing in url.
public static String sendRequest(String value, String urlString) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlString);
httppost.setHeader( "Content-Type", "application/json");
//value = "";
StringEntity stringEntity = new StringEntity(value);
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, System.getProperty("http.agent"));
httppost.setEntity(stringEntity);
HttpResponse response = httpclient.execute(httppost);
String responseString = convertStreamToString(response.getEntity().getContent());
return responseString;
} catch (Exception e) {
Log.d("check", ""+e.getMessage());
return ERROR_SERVICE_NOT_RESPONDE;
}
}
And call this method like this.
sendRequest({"player_id":1,"score":123}, "www.example.com/save_score.php");
And get json body in php and parse it.
I think you should read more documents about RESTful, Http POST and GET before starting. Your example url is GET method. It should be used for getting public information or query data. If you want to change something in server side, you should use POST method, it is more security than GET.
My recommend is using RESTful because it is painless than SOAP, especially for Android. Here is an example HTTP POST on Android.
I'm writing an Android app that should get data from a certain web application. That web app is based on Servlets and JSP, and it's not mine; it's a public library's service. What is the most elegant way of getting this data?
I tried writing my own Servlet to handle requests and responses, but I can't get it to work. Servlet forwarding cannot be done, due to different contexts, and redirection doesn't work either, since it's a POST method... I mean, sure, I can write my own form that access the library's servlet easily enough, but the result is a jsp page.. Can I turn that page into a string or something? Somehow I don't think I can.. I'm stuck.
Can I do this in some other way? With php or whatever? Or maybe get that jsp page on my web server, and then somehow extract data from it (with jQuery maybe?) and send it to Android? I really don't want to display that jsp page in a browser to my users, I would like to take that data and create my own objects with it..
Just send a HTTP request programmatically. You can use Android's builtin HttpClient API for this. Or, a bit more low level, the Java's java.net.URLConnection (see also Using java.net.URLConnection to fire and handle HTTP requests). Both are capable of sending GET/POST requests and retrieving the response back as an InputStream, byte[] or String.
At most simplest, you can perform a GET as follows:
InputStream responseBody = new URL("http://example.com").openStream();
// ...
A POST is easier to be performed with HttpClient:
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("name1", "value1"));
params.add(new BasicNameValuePair("name2", "value2"));
HttpPost post = new HttpPost("http://example.com");
post.setEntity(new UrlEncodedFormEntity(params));
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
InputStream responseBody = response.getEntity().getContent();
// ...
If you need to parse the response as HTML (I'd however wonder if that "public library service" (is it really public?) doesn't really offer XML or JSON services which are way much easier to parse), Jsoup may be a life saver as to traversing and manipulating HTML the jQuery way. It also supports sending POST requests by the way, only not as fine grained as with HttpClient.
I have successfully setup an Android App which logs-in to my drupal website.
My problem is the logged-in user session does not last very long. The site clearly shows my user as logged-in to the site, but within an hour or so the user is no longer shown as active on the site. (I am guessing because I don't really exactly know it.)
Can anyone offer an insight into why this is happening?
The code is as follows:
protected HttpResponse doInBackground(Void... params) {
// TODO Auto-generated method stub
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://mystestsite.com/testpoint/user/login");
// TODO Auto-generated method stub
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add( new BasicNameValuePair("password", "guest") );
nameValuePairs.add( new BasicNameValuePair("username", "guest") );
httpPost.setEntity( new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP post request
response = httpClient.execute(httpPost);
Log.i("SEEMS TO WORK", response.toString());
Log.v("CODE", httpPost.getRequestLine().toString() + " - " + response.toString());
}catch(Exception e){
Log.e("HTTP ERROR", e.toString());
}
return response;
}
So it sounds like it's an issue with how you're setting your cookies. When I do this kind of thing I usually just poke at my http headers until they look the same as the headers being sent form a web browser. Problem is knowing what the web browser and android app are sending so here's something to try.
This is not necessarily a code solution to your problem, but may be helpful.
Use Charles (great tool) http://www.charlesproxy.com/ for this. And no I don't have any connection to the company, it's just a great tool.
There's a feature in Charles called a reverse proxy and basically it allows you to bounce traffic through Charles to your drupal server and you can inspect it as it flows to and from your app.
Using charles you can sniff what a good request from your web browser looks like and then you can sniff what the requests from your android app look like. Compare the two and you can see where your app is badly shaping the request headers.
The debug phase goes like this:
Once you've got Charles set up, hit your drupal server a couple of times and inspect the structure of the request/response that you're seeing from the browser.
Then hit your service a couple of times from the android app and note the differences. Maybe the cookie isn't going through, maybe it's malformed, maybe there's something else about the headers. This will let you see what you need to shoot for in order to get Drupal to accept the requests.
I need to create an Android application, I'm not sure which is a better way of doing this by better I mean should I use the WebView or create an application .
I need to implement the existing application which is a ASP.NET application which mainly consists of a login screen, once the user logs in he will see a list a items in probably a gridview based on the selection from the gridview. He then will be shown more detailed info about the selected item.
The above is a web application I need to implement this as a app on Android phone.
Also there will be a need to use the GPS where based on the GPS values the department will be selected and also use the camera to take a picture and save it on to the server .
A solution which I was thinking of was to expose .NET web services and then access it in the android phone!
But I am very new to Android development and really do not how to go about this. Is there any better solution?
Can anyone help me as to how do I go about this ?
Pros:
Android App may work faster then web applications (but still depends on web page complexity)
By the help of this community and android developer site you can complete your app within a 2-3 weeks.
As you stated picture capture/upload and GPS etc are advantages of the smart phone app.
Cons:
Later, you may need iPhone, Blackberry apps!
Instead of .Net web service which typically returns XML, you can go for HTTP call with JSON response (I've seen it in Asp.net MVC). So that you can easily parse the data on android app.
Added:
HTTP call:
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(getString(R.string.WebServiceURL) + "/cfc/iphonewebservice.cfc?returnformat=json&method=validateUserLogin&username=" + URLEncoder.encode(sUserName) + "&password=" + URLEncoder.encode(sPassword,"UTF-8"));
HttpResponse response = httpClient.execute(httpGet, localContext);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse = reader.readLine();
JSONObject JResponse = new JSONObject(sResponse);
String sMessage = JResponse.getString("MESSAGE");
int success = JResponse.getInt("SUCCESS")
There are two approaches available to you:
Build an Android app.
Build a webapp, using W3C geolocation to access GPS coordinates. (see geo-location-javascript)
If you go for option (1), you'll want to expose your .NET service as a simple REST API (using JSON as Vikas suggested to make it just that bit simpler!)
Android already comes with all the components needed to access and parse such a REST API, specifically the Apache HTTP and JSON packages, and can be iterated on rather quickly once you have the basic request/parse framework in place.