Android app accesses web service - android

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.

Related

How to speed up the web service in Android?

Recently I started learning android. Now I want know information about web services in android.
which web services are fast in android?
we need to use any libraries for web service fastness?
My main aim is decrease the web service loading time.
Today I observed that web services are taking more time in below API levels and somewhat better in above API levels.
Please any one suggest me how to decrease web service loading.
If you think a library can be used then you may consider using Square Retrofit. With some benchmarks tested, it is quite snappy when considered with async task. Also you can take a look at volley which is also an option in this case but I would recommend Retrofit for its ease of use. you can consider the following article for some metrics.
Android Async HTTP Clients: Volley vs Retrofit.
JSON based web service is lightweight than XML or any other format so even in the low network connectivity you can expect considerable good performance.
Here is a sample code to connect with JSON based web service
JSONObject jsonObj = new JSONObject();
jsonObj.put("username", username);
jsonObj.put("data", dataValue);
// Create the POST object and add the parameters
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);
It's always better to make network calls inside AsyncTask so that you can show progress bar while you are dealing with web service

Get data from phpmyadmin using another machine

I am building an android app with the following code:
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.2.2/tut.php");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
System.out.println("Exception 1 caugt");
}
This apps works fine in my computer.
I want everyone download this app can use it and read the data from phpmyadmin.
can any one teach my how to do this?
(I want the data in phpmyadmin can be read from public user.)
And do I need to change the code?
HttpPost httpPost = new HttpPost("http://XXXXXXXXX/tut.php");
To make your app available to everyone you have to host your data online. There are many ways you can achieve this and it depends a lot on what type of application you intend to distribute.
If you just want to start trying out how things work you can buy a normal web hosting which supports mysql and php. This will cost you between 30 to 60 euros for a year. You setup your database, upload your php api and your good to go.
If you want a more professional approach you can choose to host in the cloud via cloud services the like of Amazon Web Services and Microsoft's Azure. This has a big learning curve but it gives you total control over the server and also huge experience.

Calling WCF in Android Application

i am new to WCF
i have created WCF which retrieve data from database and this will execute thru asp.net application
now, i want to use this WCF in my android application
can anybody tell me what should i do ?
i have study but i got little hint, about SOAP and REST.
so which would be preferable for me ? can anybody give me hint or code ?
i need ready working code snippet
URI uri = null;
try {
uri = new URI("http://localhost:3997/AWS_WCF_Service.svc");
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpGet httpget = new HttpGet(uri + "/SayHello");
httpget.setHeader("Accept", "application/json");
httpget.setHeader("Content-type", "application/json; charset=utf-8");
HttpResponse response = null;
response = httpClient.execute(httpget);
Thank YOu
Exactly how might depend on which version of ASP.Net you're using, but you will need your Web app to expose your WCF objects using a service. If you are using 4.0, either SOAP or REST services are options (Web Service or WebAPI service). If you want a philosophical debate about their respective merits, this might be a place to start: SOAP or REST for Web Services?, but since both can return JSON, either is probably fine for your Android app.
I have .Net 3.5 myself so I've mostly been using the Web Service version (with an .asmx file), and found the following link immensely useful:
Android -- How to access data in an ASP.NET database via app?
The accepted answer on that thread got me set up with a basic Web Service and little Android app in one afternoon! (This was admittedly with me having some little knowledge of both)
If you want a RESTful service and you have .Net 4.0, I suspect you could achieve your aim by following a tutorial on the subject (like this one http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api), and then using the Android code from the link above.
(Something worth bearing in mind when working with ASP.Net services returning JSON is that the returned object will be wrapped in an object called "d" - see Why do ASP.NET JSON web services return the result in 'd'?. I haven't used XML so I don't know if there are any issues for that format.)

Android app getting data from a third-party JSP & Servlet

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.

Android - Basic Authenticated HTTP Request

So basically i need my android app to connect to a web service using a url as such
"http://username:password#0.0.0.0" aka basic authentication.
obviously the username and password are checked by the web app before allowing access and otherwise doesn't allow the request.
my issue is that all the methods i try always say unauthorised (response code 401) regardless of what combination of classes and methods ive used to try and connect to the the url.
The web app in question is designed to return things only is un/pw clears otherwise it returns nothing, the web app and un/pw etc have all be checked and cleared.
so does anyone no the correct way to send a request to a url like that and have it work correctly?
android api8 btw
UPDATE
Turns out my issue is due to the web app using NTLM windows authentication which is not supported directly by androids/apache http library, investigating appropriate workarounds now
Here's some code form a really old project of mine. I used basic auth for some web service, and this worked at the time. I'm not sure if there are updated api's since then (this was Android 1.6), but it should still work.
HttpGet request = new HttpGet();
request.setURI(new URI(url));
UsernamePasswordCredentials credentials =
new UsernamePasswordCredentials(authUser, authPass);
BasicScheme scheme = new BasicScheme();
Header authorizationHeader = scheme.authenticate(credentials, request);
request.addHeader(authorizationHeader);
Basically, Basic HTTP auth is a simple hash of the user and password. The browser allows you to stuff these values in the url, but it actually does the work of adding the basic auth header to your request.

Categories

Resources