Onvif Java Library - Create a connection


This is an example for the Onvif Java Library. To run this examle you need:

  • - Java 7 or higher
  • - Newest Onvif Java Lib version (and add it to your Java project!)
  • - An available Network Video Transmitter, e.g. a PTZ camera and its IP address

A Network Video Transmitter (short: NVT) is the common term in ONVIF for your devices, like a camera. In the following steps you will connect to your NVT and use it for some basic actions.

Before you can work on your NVT, you need to create a connection to it. For that, you have to create an object of class OnvifDevice. There are two possible constructors:

OnvifDevice(String hostIp) : OnvifDevice
OnvifDevice(String hostIp, String user, String password) : OnvifDevice

You can see, both are similar and the second one just needs more information. If you have the username and password for your NVT I recommand to use these. Most operations won't work if you are not logged in. But for first connection trys you can just work with an ip address. Some methods (like getDate()) don't need authentification.
Please consider, at the moment there are no possible methods for Device discovery (but you can implement these).

import java.net.ConnectException;
import java.util.Date;

import javax.xml.soap.SOAPException;

import de.onvif.soap.OnvifDevice;

public class OnvifTest {	
   public static void main(String[] args) {
      try {
         // Replace these values with your camera data!
         OnvifDevice nvt = new OnvifDevice("192.168.0.20", "admin", "password");
      }
      catch (ConnectException e) {
         System.err.println("Could not connect to NVT.");
      }
      catch (SOAPException e) {
         e.printStackTrace();
      }
   }
}

There are two possible exceptions you have to catch. One is the ConnectException which should be thrown if you cannot connect to your NVT. Please implement a proper reaction to this exception.
The other one is the SOAPException. These get thrown if there occure any fauls while working with your device.

To test the functionality of your camera, let's print its current time:

import java.net.ConnectException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.xml.soap.SOAPException;

import de.onvif.soap.OnvifDevice;

public class OnvifTest {
   public static void main(String[] args) {
      try {
         OnvifDevice nvt = new OnvifDevice("192.168.0.20", "admin", "password");
         Date nvtDate = nvt.getDevices().getDate();
         System.out.println(new SimpleDateFormat().format(nvtDate));
      }
      catch (ConnectException e) {
         System.err.println("Could not connect to NVT.");
      }
      catch (SOAPException e) {
         e.printStackTrace();
      }
   }
}

Your output should look similar to this:

16.12.14 12:12