Android Development

Google's android guide Home Contact

Android WebServices

Webservices in android can be used to exchange data with applications running on other platforms, such as information on web, data on remote server or cloud etc. Common Webservices include "Rest" or (Representational State Transfer), "Soap" (Simple Object Access Protocol), GraphQL APIs, Web Sockets, Firebase, Google Cloud end points, and third party APIs (Twitter, Facebook, Google Maps, payment gateways etc).

In Android for parsing data, though both JSON and XML can be used, but similar to iOS it is mostly Rest (or RESTful) services, with data in JSON format, as it can be easily parsed. RESTful web services use HTTP requests (GET, POST, PUT, DELETE) to retrieve or manipulate data. RESTful APIs are stateless by design, and each API request must include all the information needed for the server to process it.

To communicate with web service, use HTTP client libraries and data serialization libraries (e.g., Gson or Moshi for JSON). For specific web service when required obtain necessary credentials (e.g., API keys, access tokens).

    JSON and XML Comparison

  • Both JSON and XML are specified formats for the exchange of structured data.
  • JSON, compared to XML, has the ability to not only provide primitive types, such as strings or numbers, but also objects and arrays.
  • JSON is considered more lightweight, easier to read and quick to parse than XML.

    Rest Webservice

    For REST web service, the standard HTTP actions are used as follows:

  • GET – Retrieves or queries for data, usually using passed criteria.
  • PUT – Creates a new entry, record.
  • DELETE – Removes a resource.
  • POST - Updates a resource or creates a resource.

  • The data that is transmitted uses standard MIME types, including images, video, text, html, XML and JSON.

    Steps to get required data from Server using Rest WebService

  1. Identify the end point URL on the server.
  2. Make appropriate HTTP call asynchrously to request data from server, specifying any request parameters.
  3. Receive server response in the requested format (JSON or XML).
  4. Parse data.
  5. Display parsed data on device screen.

    Steps to send data to Server using Rest WebService

  1. Convert data in JSON (or XML) format.
  2. Make asynchronous network request to send data using HTTP methods to the endpoint URL.
  3. Handle server response (success, failure etc).

WebService Example

An example of using webservice with HttpURLConnection class which is part of Android SDK:
        
public class MainActivity extends AppCompatActivity {
    
    private TextView textViewResult;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        textViewResult = findViewById(R.id.text_view_result);
        
        new MyAsyncTask().execute();
    }
    
    private class MyAsyncTask extends AsyncTask {
        
        @Override
        protected String doInBackground(Void... voids) {
            String result = null;
            
            try {
                // Create a URL object for the web service endpoint
                URL url = new URL("https://www.zyasin.com/jsonexample2.json"); 
                
                // Open a connection to the web service endpoint
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                
                // Set the request method to GET
                connection.setRequestMethod("GET");
                
                // Get the response code
                int responseCode = connection.getResponseCode();
                
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // Read the response data
                    InputStream inputStream = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                    StringBuilder stringBuilder = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        stringBuilder.append(line);
                    }
                    reader.close();
                    inputStream.close();
                    result = stringBuilder.toString();
                }
                
                // Disconnect the connection
                connection.disconnect();
                
            } catch (IOException e) {
                e.printStackTrace();
            }
            
            return result;
        }
        
        @Override
        protected void onPostExecute(String result) {
            if (result != null) {
                // Update the UI with the result
                textViewResult.setText(result);
            } else {
                // Handle the error
                textViewResult.setText("Error occurred");
            }
        }
    }
}


         
Here, the doInBackground method of an AsyncTask is used to make a GET request to a web service endpoint that returns a JSON object. The response data is read using a BufferedReader and converted to a string using a StringBuilder. The result is returned as a string to the onPostExecute method, which updates the UI with the result using a TextView.