Code Samples

Download REST client samples

RUBY

download arrow Download

PHP

download arrow Download

Java

download arrow Download

.NET (C#)

download arrow Download

WGet

download arrow Download

Code Sample: Consuming REST API using Java

A very important step in writing a client for BrightCloud web service is to look for an appropriate OAuth library that you can use to sign the requests, unless of course 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. These libraries, available for various languages, can reduce the time you spend implementing authorization for your app. You can review these libraries on the OAuth site: http://oauth.net/code

Continue Reading »

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. What I like about Signpost is that it 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 means that all the power and flexibility of the underlying HTTP engine is still 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 BCWS 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";
  

Let's assume that the user has previously registered with BrightCloud 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 sought -

    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 BCWS 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 bits provided above just illustrate the various pieces to consuming the BCWS REST interface which as you would have noticed, is pretty straightforward. A real time integration however would need some more time invested in integration design as well as better error handling. Listed below is the consolidated code for our sample with some error handling thrown in. Click here for downloading a professional sample in Java that not only has a better design but also serves as an illustration 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 BCWS client in Php. Since BCWS requires each request to be signed using 2-legged OAuth, a very important step in writing this client is to look for an appropriate OAuth library that you can use to sign the requests, unless of course 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 BCWS requests. For the actual communication with the server, developers can either use cURL which is available as a Php extension or they can opt for a bit lower level programming using Php Sockets. For the purpose of this sample, we'll use cURL for communication with the BrightCloud server.

Continue Reading »

So, let's get started with writing our sample client. Let's assume that the user has previously registered with BrightCloud 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 have them in Php variables -

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

Let's assume that the user wants to retrieve the classification information for the URI www.whatismyclassification.com. Let's 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 BCWS 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 sought, 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");
  

The next step is to generate the OAuth signature. This is where the Php OAuth library comes into picture. Please note that since Access Token/Secret are not required in 2-legged OAuth, we don't initialize any OAuthToken object and just use NULL for it where ever 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 service 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 BCWS 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 bits provided above just illustrate the various pieces to consuming the BCWS REST interface using Php. A real time integration with BCWS however 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 BCWS 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);