Webroot BrightCloud®
Web Services

Webroot Brightcloud® Web Services


Home

Overview

Documentation

Code Samples

Log-in or Sign up

Code Samples

Download REST client samples


Guides to use Brightcloud® Web Services code samples and consume the REST API

Consuming REST API using Java

Consuming REST API using PHP


Code Sample: Consuming REST API using Java

Unless you are planning to implement authorization on your own, you must look for an appropriate OAuth library that you can use to sign the requests to write a client for BrightCloud Web Services. Because OAuth is an open standard, you can take advantage of several open-source client libraries for OAuth. These libraries, available for various languages, can reduce the time you spend implementing authorization for your app. You can view them at http://oauth.net/code.

For the purpose of this Java sample, we'll use an OAuth library called Signpost written by Matthias Kappler. Signpost is an easy and intuitive solution for signing HTTP messages on the Java platform in conformance with the OAuth Core 1.0a, Draft 3 standard. It uses the standard Java URL class, and also supports HttpClient requests. Signpost tries to be as unobtrusive as possible. It does not wrap the entire HTTP layer and hides its features from the client. Instead, you simply pass an HttpRequest object to it, and Signpost will sign the message using the credentials it was configured with. This keeps the power and flexibility of the underlying HTTP engine at your fingertips.

Now that we have finalized the OAuth library we are going to use for signing our request, it's time to get started with writing our sample client app. For our sample, we'll assume that user wants the classification information of a given URI. As explained in the Overview document, the classification information for a URI can be requested by issuing a GET request to the following REST resource URL:

http://thor.brightcloud.com/rest/uris/uri

 

The sample should allow user to enter a URI and return comprehensive classification information for that URI.

To start with, let's define two constants, one for holding the BrightCloud Web Services REST interface endpoint URL and the other for holding the relative path for the REST resource corresponding to URI info:

public static final String REST_ENDPOINT = "http://thor.brightcloud.com:80/rest";
    public static final String URI_INFO_PATH = "/uris";

 

Assume that the user has previously registered with BrightCloud Web Services and obtained a Consumer Key and a Consumer Secret for this application. These should ideally be stored in a protected location and read on demand. For the purpose of this sample, let's store them simply as constants:

public static final String CONSUMER_KEY = "my_consumer_key";
    public static final String CONSUMER_SECRET = "my_consumer_secret";

 

Next, we ask the user to enter the URI for which the classification information is needed:

System.out.print("Enter uri: ");
    BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
    String uri = consoleReader.readLine();

 

The next step is to construct the complete REST resource URL for getting the classification information for the user provided URI. For our sample request, the resource url is constructed by appending the user provided URI (after URL Encoding it) to the full URL for URI Info resource:

String endpoint = REST_ENDPOINT + URI_INFO_PATH + "/" + uri;

 

Subsequently, we create an HTTP request to the BrightCloud Web Services REST resource and set the appropriate HTTP method:

java.net.URL endpointUrl = new java.net.URL(endpoint);
    java.net.HttpURLConnection request = (java.net.HttpURLConnection)endpointUrl.openConnection();
    request.setRequestMethod("GET");

 

The next step is to sign the request. This is where the Signpost library comes into picture:

oauth.signpost.OAuthConsumer consumer = new oauth.signpost.basic.DefaultOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET, SignatureMethod.HMAC_SHA1);
    consumer.setTokenWithSecret("", "");
    consumer.sign(request);

 

After having signed the request, the next step is to send the request:

    request.connect();

 

This is how the response is read:

  java.io.BufferedReader rd  = new java.io.BufferedReader(new java.io.InputStreamReader(request.getInputStream()));
    StringBuilder response = new StringBuilder();
    String line = null;
    while ((line = rd.readLine()) != null){
      response.append(line + '\n');
    }

 

Finally, the connection is released and the response is processed (printed to standard output in our case):

request.disconnect();
    rd.close();
    System.out.println( (response != null) ? response.toString() : "No Response");

 

The code snippets above just illustrate the various pieces for consuming the BrightCloud Web Services REST interface. Although this is relatively straightforward, a real-time integration would require some more time for integration design and error handling. The consolidated code for our sample with some error handling thrown in is listed below. Click here to download our sample Java client with examples for calling all the available methods in REST interface.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.basic.DefaultOAuthConsumer;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.signature.SignatureMethod;

public class SingleFileClient {

	public static final String REST_ENDPOINT = "http://thor.brightcloud.com/rest";
	public static final String URI_INFO_PATH = "/uris";

	public static final String CONSUMER_KEY = "my_consumer_key";
	public static final String CONSUMER_SECRET = "my_consumer_secret";

	public static void main(String[] args) throws IOException{

		System.out.print("Enter uri: ");
		BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
		String uri = consoleReader.readLine();		
		String endpoint = REST_ENDPOINT + URI_INFO_PATH + "/" uri;

		HttpURLConnection request = null;
		BufferedReader rd = null;
		StringBuilder response = null;

		try{
			URL endpointUrl = new URL(endpoint);
			request = (HttpURLConnection)endpointUrl.openConnection();
			request.setRequestMethod("GET");
			
			try{
			        OAuthConsumer consumer = new DefaultOAuthConsumer(
		        		CONSUMER_KEY, CONSUMER_SECRET, SignatureMethod.HMAC_SHA1);
			        consumer.setTokenWithSecret("", "");
			        consumer.sign(request);
			} catch(OAuthMessageSignerException ex){
				System.out.println("OAuth Signing failed - " + ex.getMessage());
			} catch(OAuthExpectationFailedException ex){
				System.out.println("OAuth failed - " + ex.getMessage());
			}
			
			request.connect();

			rd  = new BufferedReader(new InputStreamReader(request.getInputStream()));
			response = new StringBuilder();
			String line = null;
			while ((line = rd.readLine()) != null){
				response.append(line + '\n');
			}
		} catch (MalformedURLException e) {
			System.out.println("Exception: " + e.getMessage());
			//e.printStackTrace();
		} catch (ProtocolException e) {
			System.out.println("Exception: " + e.getMessage());
			//e.printStackTrace();
		} catch (IOException e) {
			System.out.println("Exception: " + e.getMessage());
			//e.printStackTrace();
		} catch (Exception e) {
			System.out.println("Exception: " + e.getMessage());
			//e.printStackTrace();
		} finally {
			try{
				request.disconnect();
			} catch(Exception e){
}

			if(rd != null){
				try{
					rd.close();
				} catch(IOException ex){
}
				rd = null;
			}
		}

		System.out.println( (response != null) ? response.toString() : "No Response");
	}
}


Code Sample: Consuming REST API using PHP

This sample demonstrates how to create a BrightCloud Web Services client in PHP. Since Web Services requires each request to be signed using 2-legged OAuth, it’s very important that you look for an appropriate OAuth library that you can use to sign the requests, unless you are planning to implement authorization on your own. Because OAuth is an open standard, you can take advantage of several open-source client libraries for OAuth available in PHP. This sample makes use of the PHP OAuth library from oauth.net for signing Web Services requests. For the actual communication with the server, developers can either use cURL, which is available as a PHP extension, or they can opt to use PHP Sockets. For this sample, we'll use cURL for communication with the BrightCloud server.

Let's get started with writing our sample client. We’ll assume that the user has previously registered with BrightCloud Web Services and obtained a Consumer Key and a Consumer Secret for this application. These should ideally be stored in a protected location and read on demand. For the purpose of this sample, let's put them in PHP variables:

    $consumer_key = "myconsumerkey";
    $consumer_secret = "myconsumersecret";

 

Assume for the example that the user wants to retrieve the classification information for the URI www.whatismyclassification.com. We’ll call it the subject URI. As explained in the Overview document, the classification information for a URI can be retrieved by issuing a GET request to the following REST resource URL:

http://thor.brightcloud.com/rest/uris/URI

 

To start with, let's define a few PHP variables, one for holding the BrightCloud Web Services REST interface endpoint URL, another for holding the relative path for the REST resource corresponding to URI classification information, yet another for holding the subject URI for which classification information is needed, and another one for holding the HTTP method:

$rest_endpoint = "http://thor.brightcloud.com:80/rest";
    $uri_info_path = "uris";
    $uri = "www.whatismyclassification.com";
    $http_method = "GET";

 

The first step is to construct the complete REST resource URL for getting the classification information for the URI. For our sample request, the resource URL is constructed by appending the subject URI (after URL Encoding it) to the full URL of URI Classification Info REST resource:

$endpoint = "$rest_endpoint/$uri_info_path/". urlencode($uri, "UTF-8");

 

Next, generate the OAuth signature. This is where the PHP OAuth library comes into picture. Note that, since Access Token/Secret are not required in 2-legged OAuth, we don't initialize any OAuthToken object and use NULL for it wherever required.

// Establish an OAuth Consumer based on Consumer Key and Consumer Secret
    $consumer = new OAuthConsumer($consumer_key, $consumer_secret, NULL);

    // Setup OAuth request - Use NULL for OAuthToken parameter
    $request = OAuthRequest::from_consumer_and_token($consumer, NULL, $http_method, $endpoint, NULL);

    // Sign the constructed OAuth request using HMAC-SHA1 - Use NULL for OAuthToken parameter
    $request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, NULL);

    // Extract OAuth header from OAuth request object and keep it handy in a variable
    $oauth_header = $request->to_header();

 

After having generated the OAuth header, the next step is to communicate with the BrightCloud Web Services using cURL library. Remember to include the OAuth header generated above as part of HTTP headers for the actual HTTP request.

    // Initialize a cURL session
    $curl = curl_init($endpoint);  

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  
    curl_setopt($curl, CURLOPT_FAILONERROR, false);  
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

    // Include OAuth Header as part of HTTP headers in the cURL request
    curl_setopt($curl, CURLOPT_HTTPHEADER, array($oauth_header));   

    // Make OAuth-signed request to the BrightCloud server and get hold of server response
    $response = curl_exec($curl);  

    if (!$response) {
      $response = curl_error($curl);  
    }
  
    // Close cURL session
    curl_close($curl);  

 

Finally the response is processed (printed to standard output in our case):

   // Process server response
    print($response);

 

The code snippets above illustrate the various pieces for consuming the BrightCloud Web Services REST interface using PHP. A real-time integration would be a little more involved, probably letting user provide the various inputs including the subject URI.

$consumer_key = "myconsumerkey";
$consumer_secret = "myconsumersecret";
$http_method = GET;
$rest_endpoint = "http://thor.brightcloud.com:80/rest";
$uri_info_path = "uris";
$uri = "www.whatismyclassification.com";

$endpoint = "$rest_endpoint/$uri_info_path/". urlencode($uri, "UTF-8");

// Establish an OAuth Consumer based on read credentials
$consumer = new OAuthConsumer($consumer_key, $consumer_secret, NULL);

// Setup OAuth request - Use NULL for OAuthToken parameter
$request = OAuthRequest::from_consumer_and_token($consumer, NULL, $http_method, $endpoint, NULL);

// Sign the constructed OAuth request using HMAC-SHA1 - Use NULL for OAuthToken parameter
$request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, NULL);

// Extract OAuth header from OAuth request object and keep it handy in a variable
$oauth_header = $request->to_header();

// Initialize a cURL session
$curl = curl_init($endpoint);  

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  
curl_setopt($curl, CURLOPT_FAILONERROR, false);  
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

// Include OAuth Header as part of HTTP headers in the cURL request
curl_setopt($curl, CURLOPT_HTTPHEADER, array($oauth_header));   

// Make OAuth-signed request to the BrightCloud server and get hold of server response
$response = curl_exec($curl);  

if (!$response) {
  $response = curl_error($curl);  
}
  
// Close cURL session
curl_close($curl);  

// Process server response
print($response);