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
Related
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.
I am using Spring for Android in a project and I need to manage the cookie store/manager. I am able to add cookies to any request by using an implementation of ClientHttpRequestInterceptor, but I would like to remove some of these when sending a request.
To be more specific, the problem I am facing is that, for Froyo, the implementation specific in Spring (with DefaultHttpClient) adds automatically to headers the cookies from CookieStore - that even if I am setting explicitly the headers. But I would like to manage these cookies myself (either remove some of them, or update their values). While for Gingerbread above (Spring implementation is done with HttpURLConnection) the cookies are added only if I am doing it myself - however I am not that sure as I don't see Spring setting any CookieHandler, but the bottom line is that I don't see them when performing a request or I can see them updated. So the issue is more specific to Froyo.
The work-around is to reset the connection factory; something like:
protected void resetCookieStoreForTemplate(RestTemplate template) {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.FROYO) {
template.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
}
}
Underneath, that seems to recreate the DefaultHttpClient and will use a new CookieStore. But that seems to me a bit ugly.
To wrap up, my question would be: does Spring for Android provide some method to expose some API for Cookie management? Just the way RestTemplate exposes some abstractions for connectivity, connection factory, message converters and so on, I would be very happy to have some abstraction for cookie management.
I've not used Spring myself but from what I've read about it, it follows the official advice and switches HTTP clients based on API version (which is quite clever, if seriously over-engineered for my liking). When using HTTPUrlConnection, as you mentioned, Spring probably doesn't change the CookieHandler. You should be seeing in-memory cookie handling, so everything should work for requests in the same app run but the cookies would be wiped when you close the app. Can you confirm this is what you're seeing?
If so, all you have to do is create a new CookieManager instance, passing it a custom CookieStore and null for the CookiePolicy to use the default.
It's unfortunate that a persistent store isn't built-in but it's not particularly difficult to write one either.
Edit: See here for a CookieStore that uses SharedPreferences (haven't tested it myself).
The ClientHttpRequestInterceptor class is a good approach when you need to pass common headers for all requests such as setting up content type, authorization etc. As far as I understood you want to pass some cookie values for specific request.
You could also achieve this via HttpEntity and HttpHeaders class.
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add("Cookie", "name=" + value);
HttpEntity requestEntity = new HttpEntity(null, requestHeaders);
ResponseEntity response = restTemplate.exchange(
"http://server/service?...",
HttpMethod.GET,
requestEntity,
Response.class);
Spring rest template does not provide any off the self solution for managing cookies. The class CookieHandler is provided by Apache not part of spring. Rest template is just a basic solution for managing request response with compare to spring core.
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.)
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 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.