Android WebServices
Webservices in Android can be used to exchange data with applications running on other platforms, such as information on the web, data on remote servers, or cloud storage. Common Webservices include "REST" (Representational State Transfer), "SOAP" (Simple Object Access Protocol), GraphQL APIs, WebSockets, Firebase, Google Cloud endpoints, and third-party APIs (e.g., Twitter, Facebook, Google Maps, payment gateways, etc.).
In Android, although both JSON and XML can be used for data parsing, RESTful services with data in JSON format are the most common. JSON is favored due to its ease of parsing. RESTful web services use HTTP requests (GET, POST, PUT, DELETE) to retrieve or manipulate data. RESTful APIs are stateless by design, meaning each API request must include all the necessary information for the server to process it.
To communicate with a web service, use HTTP client libraries and data serialization libraries (e.g., Gson or Moshi for JSON). For specific web services, obtain the necessary credentials (e.g., API keys, access tokens).
- 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 quicker to parse than XML.
JSON and XML Comparison
- GET – Retrieves or queries for data, usually using passed criteria.
- PUT – Creates a new entry or record.
- DELETE – Removes a resource.
- POST – Updates a resource or creates a resource.
REST Webservice
For REST web services, the standard HTTP actions are used as follows:The data that is transmitted uses standard MIME types, including images, video, text, HTML, XML, and JSON.
- Identify the endpoint URL on the server.
- Make an appropriate HTTP call asynchronously to request data from the server, specifying any request parameters.
- Receive the server response in the requested format (JSON or XML).
- Parse the data.
- Display the parsed data on the device screen.
Steps to Get Required Data from Server Using REST Web Service
- Convert data to JSON (or XML) format.
- Make an asynchronous network request to send data using HTTP methods to the endpoint URL.
- Handle server response (success, failure, etc.).
Steps to Send Data to Server Using REST Web Service
WebService Example
An example of using a web service with the `HttpURLConnection` class, which is part of the Android SDK: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`.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"); } } } }