NAVIADDRESS API
Java
How to use Naviaddress API in Java
Let's write a small program in Java programming language, which will receive brief information about the card at given Naviaddress and also display a list of images.

Make some preparations first

Naviaddress API returns data in JSON format, so to work with this data format we need a special parsing library. To solve this task, you can use the Google solution - Gson package.

Download the library file here using the Download / jar menu in the upper right corner and put it in the same directory where your program is saved. The library version number may be changed afterwards. As of writing this it was 2.8.5.
Using your favorite code editor create a new file for our future Jnavi.java program and make the skeleton code of the future program.

At the top of the file define the directives to import the required classes:

  • to work with classes
  • to work with HTTP requests
  • to work with Gson for parsing of JSON objects

    Please note that Naviaddress API uses a secure connection and allows you to connect via HTTPS protocol.
    import java.util.List;
    
    import java.io.BufferedReader;
    import java.io.DataOutputStream;
    import java.io.InputStreamReader;
    import javax.net.ssl.HttpsURLConnection;
    import java.net.URL;
    
    import com.google.gson.Gson;
    Let's create the skeleton of our future program, which, as usual, will be called using the main () method.

    Please note that for correct operation of the program we will need to handle the Exception using the try/catch block.
    public class Jnavi {
    	public static void main(String[] args) {
    	    try { 
    
    	    	// our main program code will be here
    
    	    } catch(Exception e) { 
    	        throw new RuntimeException(e); 
    	    }		
    	}
    }
    First of all, let's make GET request to the Naviaddress server and retrieve a string with data containing JSON object. In the code fragment below we prepare the request and set its parameters:

    • GET request method
    • type of returned value (we need data in JSON format)
      	    	// Prepare the request
      	        URL url = new URL("https://staging-api.naviaddress.com/api/v1.5/Addresses/7/0022"); 
      	        HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); 
      
      	       // Set up the request parameters
      			con.setRequestMethod("GET");
      			con.setRequestProperty("User-Agent", "application/json");
      Now it's time to get a server response which primarily will be saved to a buffer stringBuffer and then – in the result of some simple manipulations - converted to a string jsonString.

      Finally, let's display the results.
      			// Get the response to a buffer
      			BufferedReader in = new BufferedReader(
      			        new InputStreamReader(con.getInputStream()));
      
      			String inputLine;
      			StringBuffer stringBuffer = new StringBuffer();
      
      			// Convert data from the buffer to a string
      			while ((inputLine = in.readLine()) != null) {
      				stringBuffer.append(inputLine);
      			}
      			in.close();
      
      		// Get the response
      			String jsonString = stringBuffer.toString();
      
      			// Print out the results
      			System.out.println(jsonString);
      Ta-dah! Our program is ready, now you can compile and run it.
      > javac Jnavi.java
      > java Jnavi
      If we did everything right, then we should get such a message on the screen of the console. It seems clear that we've got a JSON object (as required).
      {"result":{"address_description":{},"address_type":"premium","booking":{},"category":{"id":10},"contacts":[{"type":"phone","value":"7 (499) 253-11-83"},{"type":"vkontakte","value":"https://vk.com/naviaddress"},{"type":"instagram","value":"https://instagram.com/naviaddress"},{"type":"website","value":"https://naviaddress.com"}, ...
      Handle JSON data

      Great, now for further work we'll need to convert JSON to another object format more familiar to Java. A full description of the data structures returned from the Naviaddress server is available at swagger.naviaddress.com.

      Let's create a special set of utility classes which we'll convert the resulting object into.

      • Response class - in fact, it is a wrapping class where we are only interested in the value of the result field
      • Result class - the server returns a structure with the data of the address on the request (GET Addresses). For this example, we are interested in the fields container, naviaddress and description.
      • Cover class contains information on the photos used for the Navi card design. They are provided as a list of values of CoverImage type.
      • CoverImage class describes each of naviadress photos. In the image field is the URL to the photo.
      For convenience, we have added a string conversion function toString () to each class.

      class Response {
        public Result result;
      
        public String toString() {
        	return result.toString();// + " - " + description;
        }
      }
      
      class Result {
        public String description;
        public String container;
        public String naviaddress;
        public List<CoverImage> cover;
      
        public String toString() {
        	String s = "Address:";
        	s += "[" + container + "]" + naviaddress + " - " + description + "\n";
        	s += "Images:\n";
        	for(int i=0;i<cover.size();i++) {
        		s += Integer.toString(i)+": "+cover.get(i).toString() + "\n";
        	}
        	return s;
        }
      }
      
      class CoverImage {
        public String image;
        public String toString() {
        	return image;
        }
      }
      
      Now we'll comment out the printout of the string with the object - we need it no more - we will printout the already structured data.
      // Print out the results
      // System.out.println(jsonString);
      
      The program is almost ready. The only we need is to convert the previously received jsonString string into an object of the Response class. We will do this using the fromJson() method of Gson library.

      In conclusion, we'll printout the resulting object.

      			Gson gson = new Gson();
      			Response response = gson.fromJson(jsonString, Response.class);
      
      			System.out.println(response.toString());
      Since we use the Gson library we need to slightly change the parameters of the Java compiler and the JVM interpreter. For this purpose, we'll add the -cp (or -classpath) parameter to the command line.
      > javac -cp gson-2.8.5.jar:. Jnavi.java
      > java -cp gson-2.8.5.jar:. Jnavi
      If we did it right, then we should receive full information about the given naviaddress:

      • its container and address

      • title

      • URL list of cover images

      In output we should receive something like the following code that contains information on the given address:

      Address:7495 - Office Naviaddress.ru
      Images:
      0: https://navi-images.s3.eu-west-3.amazonaws.com/uploads/images2/1616/large_OPWKWILRLD.png
      1: https://navi-images.s3.eu-west-3.amazonaws.com/uploads/images2/1616/large_DOJWEQWRZZ.png
      2: https://navi-images.s3.eu-west-3.amazonaws.com/uploads/images2/1616/large_CDOPDXPCRQ.png
      You can download the full Jnavi.java program code here.

      You can download the required Gson library here.

      written by: A.Gershun (09/12/2018)

      Made on
      Tilda