How to communicate with Web services in your applications?

Well, there is no short answer to this question. You can follow one of the communication techniques including a smoke signal.

I hope you had fun with my smoke signal joke. Now, we are going to sail to the web client’s ocean. Although there are many various web services on the internet, their communication languages are not so much as a type of web services. A famous common language between web servers and clients are XML and JSON language.  Before JSON came out, XML language was very memorable, almost every web services were accepting XML encoded documents or request bodies.

A Simple XML document consists of tags like HTML. To illustrate, “CATALOG” is a tag and it spans “CD” blocks, and “MUSIC” blocks span “TITLE”, “ARTIST” block.

<CATALOG>
<MUSIC>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Hide your heart</TITLE>
<ARTIST>Bonnie Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</MUSIC>
</CATALOG>

Another common language is JSON. This common language is famous nowadays, so if you learn JSON, you will be ok for a while until next common language.

If we want to rewrite our XML document in JSON format;

[
   {
      "TITLE": "Empire Burlesque",
      "ARTIST": "Bob Dylan",
      "COUNTRY": "USA",
      "COMPANY": "Columbia",
      "PRICE": "10.90",
      "YEAR": "1985"
   },
   {
      "TITLE": "Hide your heart",
      "ARTIST": "Bonnie Tyler",
      "COUNTRY": "UK",
      "COMPANY": "CBS Records",
      "PRICE": "9.90",
      "YEAR": "1988"
   }
]

So, which one is simple? I can hear your answer that is JSON. Put your prejudice away from you, look at this link. I think for now this information about common language is enough.

You can use any web service client to add web service communication support to your application. You can use “http.client.” for a Python-based project or “Retrofit” is a great choice for a JAVA-based project but you can find many web client frameworks on the internet. In this tutorial, I will explain “http.client” and “Retrofit”.

Let’s assume that we have two API calls in our web service whose address is “https://10.0.0.1:8443”. First API call is “addmusic” and the last one is “getmusics”. We can assume that the SSL certificate for this imaginary web service is a self-signed certificate.

“addmusic” API Call

Addmusic API Call
API URL: https://10.0.0.1:8443/addmusic
Method: POST
Request Body: { “TITLE”: “Empire Burlesque”,

“ARTIST”: “Bob Dylan”,

“COUNTRY”: “USA”,

“COMPANY”: “Columbia”,

“PRICE”: “10.90”,

“YEAR”: “1985”}

Table 1

“getmusics” API Call

Get Musics API Call
API URL: https://10.0.0.1:8443/addmusic<user-id>
Method: GET
Request Body:
Response Body: [{ “TITLE”: “Empire Burlesque”, “ARTIST”: “Bob Dylan”, “COUNTRY”: “USA”, “COMPANY”: “Columbia”, “PRICE”: “10.90”, “YEAR”: “1985” },

{ “TITLE”: “Hide your heart”, “ARTIST”: “Bonnie Tyler”, “COUNTRY”: “UK”, “COMPANY”: “CBS Records”, “PRICE”: “9.90”, “YEAR”: “1988” }]

Table 2

 

Table 1,2 shows how to construct proper requests to get responses from web service.

 

“Http.client” A Native Python Library

“addmusic” API Call

import json
import http.client
import ssl

connection = http.client.HTTPSConnection('10.0.0.1:8443',timeout=5, context=ssl._create_unverified_context())
headers = {'Content-type': 'application/json'}

responseBody = {
"TITLE": "Empire Burlesque",
"ARTIST": "Bob Dylan",
"COUNTRY": "USA",
"COMPANY": "Columbia",
"PRICE": "10.90",
"YEAR": "1985"
}

responseBodyJSON = json.dumps(responseBody)
connection.request('POST', '/addmusic/',responseBodyJSON, headers)
response = connection.getresponse()

print(response.status)
print(response.reason)
print(response.read())

After importing necessary packages, in line 5 secure HTTP connection is created with the server address, a timeout, and a context argument. “http.client’ tends to use https protocol with an only CA-signed certificate, not a self-signed certificate due to security concerns. However, you are still to use “http.client” object with a self-signed certificate by proving the specific context variable, “ssl._create_unverified_context”.

Each HTTP connection requires “Content-type” field to identify it’s format of a request body, in our case we provided “application/json” because we are sending JSON object in the request body.  Line 8-15 defines request body variable and line 17 convert request body to JSON formatted string.

A request is finally constructed and executed at Line 18, after that response is received at the following line. Line 21-23 is for printing result of a request.

“getmusics” API Call

import json
import http.client
import ssl

connection = http.client.HTTPSConnection('10.109.143.88:8443',timeout=5, context=ssl._create_unverified_context())

headers = {'Content-type': 'application/json'}

connection.request('GET', '/getsensorvalues/6029718/',None, headers)

response = connection.getresponse()

print(response.status)
print(response.reason)
print(response.read())

“Retrofit” Third Party JAVA Library

Retrofit is a type-safe HTTP client library for your project. If you want to save some time while you are developing your project, Retrofit library is your great candidate. If you want to access more information about Retrofit, you can refer to this link.

Retrofit implementation of a project usually consists of many JAVA annotations and an interface.

Implementing to your project is more complicated than “http.client” library; however, once you learn this, you will not consume much time to import Retrofit to your project.

Let me tell you my strategy that I use to import this library to my project.

  1. Create a Singleton Manager Class like “XXXXConnectionManager.java“. This class usually contains a base web service URL string, and an interface instance that has web service API call functions.
  2. Create an Interface that will contain API call functions. I prefer to give a name like “XXXXConnectionMethods.java”. 
  3. Create model object class for request and responses to utilize POJO support.
  4. After third steps you can use your instance in your project, I am going to explain how you are going to use it in following titles.

 

Creating the Singleton Manager Class For Web Service Client

Let’s our server address is “10.0.0.1” and its port number is 9997. Although we started with the web service that has a self-signed certificate, we will continue writing a web service client for web services that do not have self-signed certificate.

Here is our the singleton web service manager class.

public class XXXXConnectionManager {

    private static XXXXConnectionManager self;
    private XXXXConnectionManagerMethods methods;

    public static XXXXConnectionManager getInstance()
    {
        if(self == null)
            self = new XXXXConnectionManager();
        return self;

    }
    public void setConnectionMethods(XXXXConnectionManagerMethods methods) {
        this.XXXXConnectionManagerMethods = methods;
    }

    public void reConfigureClient()
    {
        Retrofit retrofit = new Retrofit.Builder().baseUrl("http://"+"10.0.0.1"+":9997"+"/").addConverterFactory(GsonConverterFactory.create()).build();
        methods = retrofit.create(XXXXConnectionManagerMethods.class);
    }

    public XXXXConnectionManager()
    {

        reConfigureClient();    
    }
}

 

In addition to web service manager class, you need to implement the XXXXConnectionManagerMethods interface class for declaring web service methods.

“addmusic” API Call and “getmusics” API Call

public interface XXXXConnectionManagerMethods {

    @GET("getmusics")
    Call<GetMusicResponse> getMusics();

    @POST("addmusic")
    Call<AddMusicResponse> addMusic(@Body Music requestBody);

}

Now you declared our web service methods to the Retrofit library, then you have to provide model classes such as GetMusicRequest, AddMusicResponse, and so on.

You can find model classes in the following code snippets, then you can get an idea to write your model classes.

public class Music {
    private String TITLE;
    private String ARTIST;
    private String COUNTRY;
    private String COMPANY;
    private double PRICE;
    private  int   YEAR;
    public String getTITLE() {
        return TITLE;
    }

    public void setTITLE(String TITLE) {
        this.TITLE = TITLE;
    }

    public String getARTIST() {
        return ARTIST;
    }

    public void setARTIST(String ARTIST) {
        this.ARTIST = ARTIST;
    }

    public String getCOUNTRY() {
        return COUNTRY;
    }

    public void setCOUNTRY(String COUNTRY) {
        this.COUNTRY = COUNTRY;
    }

    public String getCOMPANY() {
        return COMPANY;
    }

    public void setCOMPANY(String COMPANY) {
        this.COMPANY = COMPANY;
    }

    public double getPRICE() {
        return PRICE;
    }

    public void setPRICE(double PRICE) {
        this.PRICE = PRICE;
    }

    public int getYEAR() {
        return YEAR;
    }

    public void setYEAR(int YEAR) {
        this.YEAR = YEAR;
    }
}

Now you defined your base model class in the “Music” JAVA class.

public class AddMusicResponse {
    private ProjectConstants.OPERATION_RESULT operationResult;
    public AddMusicResponse() {
    }
    public ProjectConstants.OPERATION_RESULT getOperationResult() {

        return operationResult;
    }
    public void setOperationResult(ProjectConstants.OPERATION_RESULT operationResult) {
        this.operationResult = operationResult;
    }
}
public class GetMusicResponse {
    ArrayList<Music> musics;
    private ProjectConstants.OPERATION_RESULT operationResult;

    public GetMusicResponse() {
    musics = new ArrayList<>();
    }

    public ArrayList<Music> getMusics()
    {
     return musics;
    }

    public ProjectConstants.OPERATION_RESULT getOperationResult() {

        return operationResult;
    }

    public void setOperationResult(ProjectConstants.OPERATION_RESULT operationResult) {
        this.operationResult = operationResult;
    }
}

Congratulations you completed your web service client software, now you can get music information from the web service or add new music to the web service.

Leave a Reply

Your email address will not be published. Required fields are marked *