Using Web Services from Android

Web Services can be used in Android as in any other Java program, except that here we need to remember a few additional requirements. Since the use of network services involves the use of a network (as the name implies :)), we need to take care of the appropriate application permissions. In this title we add an entry:

 

<uses-permission android: name = “android.permission.INTERNET”  />

after the tag a before. There is another very important issue – if we want to use it in an application from a web service, we have to do it in a separate thread. If we forget about it, Android will remind us of this by throwing a message on the console:

StrictMode $ AndroidBlockGuardPolicy

I did this using a separate class inherited from AsyncTask, though if you want you can apply a regular Thread object. In the following illustration, I read the content of our website and displayed it on the console.

 

 

Score displayed on console:

 

This is just the source code for a web page, but it could also be a XML data file.

Alternatively, we can use the ready-to-use HttpClient library from Apache, so that we do not have to focus so much on the details of the stream reading implementation. The effect is essentially the same, another form. Here we also have to remember to separate the thread.

 

Let’s now take a look at XML objects using network services. I dumped the sample XML resource to the server for processing. This file will remain there so you can use it.

Based on the previous solution, I converted the class of Watek. The code responsible for retrieving the data was transferred to a separate method givingData. By the way, I made this so that the server address, port and resource passed by the parameters of the method and not doing it “stiff”. I also gave the dawajXml method using the given methodData will receive data as a String and will return as a DOM object:

 

The doInBackground method uses the previously described methods and receives the DOM object. The onCreate method remains unchanged: