HttpOperations Code Examples

Description

The code examples for method calls in this document reference a class called HttpOperations to perform some repetitive programming tasks. This class is not part of the AgilePoint REST API. The examples here are provided so that you can modify them to do whatever similar tasks you need for your software.

Java Code Example

package restExamples;

import java.io.IOException;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HTTPOperations {

  String domain = "";
  String userName = "";
  String password = "";
  String appID = "";
  String locale = "";

  public HTTPOperations(String domain, String userName, String password,
      String appID, String locale) {
    this.domain = domain;
    this.userName = userName;
    this.password = password;
    this.appID = appID;
    this.locale = locale;
  }

  public String GETMethod(String URI) {
    org.apache.http.impl.client.CloseableHttpClient httpClient = null;
    org.apache.http.client.methods.CloseableHttpResponse response = null;
    httpClient = HttpClients.createDefault();
    org.apache.http.client.methods.HttpGet httpget = null;

    httpget = new HttpGet(URI);
    httpget.addHeader("content-type", "application/json;charset=UTF-8");
    httpget.addHeader(
        "Authorization",
        "Basic "
            + new String(Base64.encodeBase64((domain + "\\"
                + userName + ":" + password).getBytes())));
    httpget.addHeader("AppName", "RESTTest");
    httpget.addHeader("Locale", "en-US");

    try {
      response = httpClient.execute(httpget);
      return EntityUtils.toString(response.getEntity());
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return "";
  }

  public String POSTMethod(String URI, String jsonRequestData) {
    org.apache.http.impl.client.CloseableHttpClient httpClient = null;
    org.apache.http.client.methods.CloseableHttpResponse response = null;
    httpClient = HttpClients.createDefault();
    org.apache.http.client.methods.HttpPost httppost = null;

    httppost = new HttpPost(URI);
    httppost.addHeader("content-type", "application/json;charset=UTF-8");
    httppost.addHeader(
        "Authorization",
        "Basic "
            + new String(Base64.encodeBase64((domain + "\\"
                + userName + ":" + password).getBytes())));
    httppost.addHeader("AppName", "RESTTest");
    httppost.addHeader("Locale", "en-US");

    try {
      StringEntity se = new StringEntity(jsonRequestData,
          ContentType.create("text/plain", "UTF-8"));
      httppost.setEntity(se);
      response = httpClient.execute(httppost);
      return EntityUtils.toString(response.getEntity());
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return "";
  }

  public String POSTMethodXML(String URI, String xmlRequestData) {
    org.apache.http.impl.client.CloseableHttpClient httpClient = null;
    org.apache.http.client.methods.CloseableHttpResponse response = null;
    httpClient = HttpClients.createDefault();
    org.apache.http.client.methods.HttpPost httppost = null;

    httppost = new HttpPost(URI);
    httppost.addHeader("content-type", "application/xml;charset=UTF-8");
    httppost.addHeader(
        "Authorization",
        "Basic "
            + new String(Base64.encodeBase64((domain + "\\"
                + userName + ":" + password).getBytes())));
    httppost.addHeader("AppName", "RESTTest");
    httppost.addHeader("Locale", "en-US");

    try {
      StringEntity se = new StringEntity(xmlRequestData,
          ContentType.create("text/plain", "UTF-8"));
      httppost.setEntity(se);
      response = httpClient.execute(httppost);
      return EntityUtils.toString(response.getEntity());
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return "";
  }
  
}

C# Code Example

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Xml.Linq;
using System.Xml;

namespace RestExamples
{
  public class HTTPOperations
  {
    string domain = string.Empty;
    string userName = string.Empty;
    string password = string.Empty;
    string appID = string.Empty;
    string locale = string.Empty;
    string contenttype = string.Empty;

    public HTTPOperations(string Domain,string UserName,string Password,string AppID, string Locale)
    {
      domain = Domain;
      userName = UserName;
      password = Password;
      appID = AppID;
      locale = Locale;
    }

    #region Create Http Request

    public HttpWebRequest GetHttpRequest(string URI, string Method)
    {
      //---------- Creat a request with required URI
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URI);

      request.Method = Method;

      //Set Content Type
      request.ContentType = "application/json";
      //Set Accept Type
      request.Accept = "application/json";

      //Setting Header
      //Creating Authorizationheader format (Basic (base64(domain\\username:password))
      request.Headers[HttpRequestHeader.Authorization] =
        "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(domain + "\\" + userName + ":" + password));
      request.Headers["appID"] = appID;
      request.Headers["locale"] = locale;
      //request.Timeout = 100000;
      //request.KeepAlive = false;
      //ServicePointManager.ServerCertificateValidationCallback += 
      //         new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate);
      return request;
    } 

    #endregion

    #region POST Method

    public string POSTMethod(string URI, string JsonRequestData)
    {

      HttpWebRequest request = GetHttpRequest(URI, WebRequestMethods.Http.Post);

      //------------POST ing data to Server

      request.ContentLength = JsonRequestData.Length;
      Stream content = request.GetRequestStream();
      StreamWriter ContentWriter = new StreamWriter(content);
      ContentWriter.Write(JsonRequestData);
      ContentWriter.Close();

      HttpWebResponse webResponse = null;
      try
      {
        //-------- geting response from request
        webResponse = (HttpWebResponse)request.GetResponse();
      }
      catch (WebException ex)
      {
        throw ex;
      }

      string jsonResponseData = ReadData(webResponse);

      return jsonResponseData;

    }
         
    public string PostXml(string url, string xml)
    {
      try
      {
        byte[] bytes = Encoding.UTF8.GetBytes(xml);
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        request.ContentLength = bytes.Length;
        request.ContentType = "application/xml";
        using (Stream requestStream = request.GetRequestStream())
        {
          requestStream.Write(bytes, 0, bytes.Length);
        }
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream resStream = response.GetResponseStream();
        StreamReader rdStreamRdr = new StreamReader(resStream);
        if (response.StatusCode != HttpStatusCode.OK)
        {
          string message = String.Format("POST failed. Received HTTP {0}",
          response.StatusCode);
          throw new ApplicationException(message);
        }
        else
        {
          string message = rdStreamRdr.ReadToEnd();         
          return message;
        }
      }
      catch (Exception)
      {
        throw;
      }

    }

    public string POSTMethod(string URI)
    {
      HttpWebRequest request = GetHttpRequest(URI, WebRequestMethods.Http.Post);

      //------------POST ing data to Server

      //request.ContentLength = JsonRequestData.Length;
      Stream content = request.GetRequestStream();
      StreamWriter ContentWriter = new StreamWriter(content);
      //ContentWriter.Write();
      ContentWriter.Close();

      HttpWebResponse webResponse = null;
      try
      {
        //-------- geting response from request
        webResponse = (HttpWebResponse)request.GetResponse();
      }
      catch (WebException ex)
      {
        throw ex;
      }

      string jsonResponseData = ReadData(webResponse);

      return jsonResponseData;
    }

    #endregion

    #region GET Method

    public string GetData(string URI)
    {
      HttpWebRequest request = GetHttpRequest(URI, WebRequestMethods.Http.Get);
      try
      {
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        string jsonResponseData = ReadData(response);

        return jsonResponseData;
      }
      //HttpWebResponse response = request.GetResponse() as HttpWebResponse;
      catch (Exception ex)
      {
        //LogServiceException(ex);
        throw ex;
      }
            
    }

    #endregion

    string ReadData(HttpWebResponse webResponse)
    {
      string jsonResponseData = string.Empty;
      try
      {
        if (webResponse.StatusCode == HttpStatusCode.OK)
        {
          //Stream webStream = webResponse.GetResponseStream();
          StreamReader responseReader = new StreamReader(webResponse.GetResponseStream());
          jsonResponseData = responseReader.ReadToEnd();

          responseReader.Close();
        }
      }
      catch (Exception ex)
      {
        throw ex;
      }

      return jsonResponseData;
    }

  }
}

Code Examples in the AgilePoint NX Documentation

The AgilePoint NX Product Documentation is intended as a basic reference to help you understand how to complete basic coding tasks, such as make API or JavaScript method calls. Code examples that show specific use cases, the solutions to specific business problems, or detailed implementation scenarios are outside the scope of the AgilePoint NX Product Documentation. For specific and/or advanced types of examples that may better meet your requirements, AgilePoint provides several resources:

  • AgilePoint Community Forums - A free, AgilePoint-moderated, crowd-sourcing user forum where you can ask questions about specific techniques, the solutions to use cases, workarounds, or other topics that may not be covered in the Product Documentation.
  • Professional Services - If you can not find the information you need for your specific business problem, mentoring is available through AgilePoint Professional Services.
  • Personalized Training - AgilePoint can provide personalized training for your organization. To request personalized training, contact AgilePoint Sales.