HTTPScriptable

From Dreamtsoft Wiki
Jump to: navigation, search

Overview

Dreamtsoft provides an HTTP interface for sending GET, POST, PUT and DELETE requests from your Dreamtsoft site.

Usage

  var HTTPScriptable = require('core/HTTPScriptable');
  var http = new HTTPScripable();
  http.setURL(....);
  ...

An HTTP request consists of the following parts:

  URL: scheme://domain/path?query_parameters
  BODY: request_body

The following APIs are used to build the URL and BODY for the request:

  • new HTTP(url)
    • the URL for the request, may contain query parameters after the '?' in the URL
  • addURLParameter(name, value)
    • the parameter is added to the URL for the request, the value is URI encoded
  • addRequestParameter(name, value)
    • the parameter is added to either to the URL (value is URI encoded) or to the request body depending on the rules below
  • setRequestBody(body)
    • the request is sent with the contents of 'body' as the request body

Rules:

  • anything set in the 'url' as part of the constructor will be sent as the URL
  • anything set in 'setRequestBody' will be set sent as the BODY
  • for GET, HEAD and DELETE requests
    • any addURLParameter pairs are appended to the URL with the value encoded
    • any addRequestParameter pairs are appended to the URL with the value encoded (this makes addRequestParameter the same as addURLParameter in this case)
    • setRequestBody is not allowed for GET, HEAD and DELETE methods - it is simply ignored
  • for POST and PUT methods,
    • any addURLParameter pairs are appended to the URL with the value encoded
    • if the BODY is set using 'setRequestBody' then any addRequestParameter pairs are appended to the URL with the value encoded (otherwise, they would mess up the request body already set)
    • if the BODY is NOT set using 'setRequestBody' then any addRequestParameter pairs are encoded and sent as the BODY

API

new

  /**
   * Create HTTP client using the supplied URL
   * 
   * @param url - url string, including http[s]:// scheme prefix and may contain ?query_parameters
   *            Note: if the URL is not specified it may be added later using 'setURL'
   */
  new HTTPScriptable(String url)

setURL

  /**
   * Set the URL endpoint to send request to
   *
   * @param url - url string, including http[s]:// scheme prefix and may contain ?query_parameters
   */
  setURL(String url)

setUrl

  /**
   * Set the URL endpoint to send request to
   *
   * @param url - url string, including http[s]:// scheme prefix and may contain ?query_parameters
   */
  setUrl(String url)

setRequestMethod

  /**
   * Set the request method to use 
   * 
   * @param method GET, POST, PUT or DELETE
   */
  setRequestMethod(String method)

addRequestParameter

  /**
   * Add a request parameter to the request
   *
   * @param name - name of parameter
   * @param value - value of the parameter (the value is properly URI encoded if needed)
   */
  addRequestParameter(String name, Object value)

setCookie

  /**
   * Set a cookie to be sent with the request
   *
   * @param name - name of cookie
   * @param value - value of the cookie               
   */
  setCookie(String name, String value)

getCookie

  /**
   * Get the value of a cookie set with setCookie
   *
   * @param name - name of cookie
   *             
   * @return value of the cookie
   */
  String getCookie(String name)

setTrustAllSSL

  /**
   * Trust SSL connections without validating the certificate
   * 
   * @param b if true, trust SSL connections, otherwise, validate certificate
   */
  setTrustAllSSL(boolean b)

setAuth

  /**
   * Set username and password for authentication of request
   * 
   * @param username
   * @param password
   * @param preemptiveAuth - if true, preemptive authorization is used
   */
  setAuth(String username, String password, Object preemptiveAuth)

setBasicAuthentication

  /**
   * Set username and password for authentication of request for use with Basic Authentication
   *
   * @param username
   * @param password
   * @param preemptiveAuth - if true, preemptive authorization is used
   */
  setBasicAuthentication(String username, String password, Object preemptiveAuth)

SetHeader

  /**
   * Set a request header
   * 
   * @param name - name of the request header
   * @param value - value for the request header
   */
  setHeader(String name, Object value)

setRequestBody

  /**
   * Set the request body
   *
   * @param body - if string, use as is.  Othereise, convert the object to a string, typically with JSON.stringify
   * @param contentType - optional, Content-Type header is set using this value.  The following shortcuts are supported:
   *         
   *    contentType    Content-Type header value
   *    -----------    -------------------------  
   *    form           application/x-www-form-urlencoded; charset=UTF-8
   *    text           text/plain; charset=UTF-8
   *    json           application/json; charset=UTF-8
   */
  setRequestBody(Object body, Object contentType)

setRequestBodyAsUploadFile

  /**
   * Set the request body as a file
   *
   * @param bucket - bucket of file
   * @param file - id of file
   * @parm file type - type of file, example: "application/pdf"
   *         
   */
  setRequestBodyAsUploadFile(bucket, file id, file type)

setTimeout

  /**
   * Set request timeouts
   * 
   * @param connTimeoutMS - connection timeout (default is 60 seconds)
   * @param socketTimeoutMS - socket timeout after connection (default is 60 seconds)
   */
  setTimeout(int connTimeoutMS, int socketTimeoutMS)

getStatusCode

  /**
   * Get the response status code after making the HTTP request
   * 
   * @return HTTP status response (200, 404, etc.)
   */
  int getStatusCode()

getReason

  /**
   * Get the reason string after making the HTTP request
   * 
   * @return HTTP reason string returned with status code
   */
  String getReason()

getString

  /**
   * Issue GET request and return response data as a string
   *
   * @param path optional, url path (does not include the scheme and domain)
   *             
   * @return response body returned by the request as a string            
   */
  String getString(Object path)

head

  /**
   * Make an HTTP HEAD request
   * 
   * @return HTTPResponseScriptable object
   */
  HTTPResponseScriptable head()

get

  /**
   * Make an HTTP GET request
   *
   * @return HTTPResponseScriptable object
   */
  HTTPResponseScriptable get()

post

  /**
   * Make an HTTP POST request
   *
   * @return HTTPResponseScriptable object
   */
  HTTPResponseScriptable post()

put

  /**
   * Make an HTTP PUT request
   *
   * @return HTTPResponseScriptable object
   */
  HTTPResponseScriptable put()

del

  /**
   * Make an HTTP DELETE request
   *
   * @return HTTPResponseScriptable object
   */
  HTTPResponseScriptable del()

getResponse

  /**
   * Make an HTTP request (should have already called setMethod)
   *
   * @return HTTPResponseScriptable object
   */
  HTTPResponseScriptable getResponse()

invoke

  /**
   * Make an HTTP request (should have already called setMethod)
   *
   * @return HTTPResponseScriptable object
   */
  HTTPResponseScriptable invoke()

send

  /**
   * Perform HTTP GET or POST based on options
   *
   * @param url     url to send request to
   * @param options object that specifies how to make the request
   *          type
   *             'GET' or 'POST' or 'DELETE' or 'PUT'
   *                  
   *          contentType
   *             content type of request (if not specified, set based on dataType)
   *                  
   *          dataType
   *             type of data being sent to server ('json', 'text', 'form')
   *             default is 'form' which is a set of name=value pairs as contentType 'application/x-www-form-urlencoded; charset=UTF-8'
   *                  
   *          data
   *             data to be sent to server (GET: append to url, POST: send as request payload)
   *
   * @return response string
   */
  String send(String url, NativeObject options)

Examples

The most common usage of the HTTP interface will be for issuing GET or PUT requests to various URLs.

GET and POST Dreamtsoft Users and Groups

  var HTTPScriptable = require("core/HTTPScriptable");
  var client = new HTTPScriptable("http://localhost:8080/io/bucket/search/user"); 
  client.setBasicAuthentication("admin", "admin");
  client.addRequestParameter("q", JSON.stringify([[["name","begins","a"]]]));
  var userResponse = client.get();
  console.log("User query got HTTP code: " + userResponse.getResponseCode());
  var userObject = JSON.parse(userResponse.getResponseBody());
  for (var i = 0; i < userObject.data.length; i++) {
     console.log("User name begins with a: " + userObject.data[i].name);
  }

  client.setUrl("http://localhost:8080/io/bucket/insert/user");
  client.setRequestBody(JSON.stringify({
     "data":  [
        { "first_name": "Ansel", "last_name": "Adams", "gender": "Male", "user_id": "ansel.adams" }
     ]
  }));
  var insertResponse = client.post();
  console.log("Insert response:\n" + insertResponse.getResponseBody());