Sample Code

The following three types of codes show how to sign a request and how to use an HTTP client to send an HTTPS request:

AccessService: indicates the abstract class that converts the GET, POST, PUT, and DELETE methods into the access method.

Demo: indicates the execution entry used to simulate GET, POST, PUT, and DELETE request sending.

AccessServiceImpl: indicates the implementation of the access method, which contains the codes required for API gateway communication.

For details about region and serviceName in the following codes, see Regions and Endpoints:

AccessService.java:

package com.cloud.apigateway.sdk.demo;

import java.io.InputStream;
import java.net.URL;
import java.util.Map;

import org.apache.http.HttpResponse;

import com.cloud.sdk.http.HttpMethodName;

public abstract class AccessService {
    
    protected String serviceName = null;
    
    protected String region = null;
    
    protected String ak = null;
    
    protected String sk = null;
   
    public AccessService(String serviceName, String region, String ak, String sk) {
        this.region = region;
        this.serviceName = serviceName;
        this.ak = ak;
        this.sk = sk;
    }
    
    public abstract HttpResponse access(URL url, Map<String, String> header, InputStream content, Long contentLength,
        HttpMethodName httpMethod) throws Exception;
        
    public HttpResponse access(URL url, Map<String, String> header, HttpMethodName httpMethod) throws Exception {
        return this.access(url, header, null, 0l, httpMethod);
    }
    
    public HttpResponse access(URL url, InputStream content, Long contentLength, HttpMethodName httpMethod)
        throws Exception {
        return this.access(url, null, content, contentLength, httpMethod);
    }
    public HttpResponse access(URL url, HttpMethodName httpMethod) throws Exception {
        return this.access(url, null, null, 0l, httpMethod);
    }
    
    public abstract void close();
    
    public String getServiceName() {
        return serviceName;
    }
    
    public void setServiceName(String serviceName) {
        this.serviceName = serviceName;
    }
    
    public String getRegion() {
        return region;
    }
    
    public void setRegion(String region) {
        this.region = region;
    }
    
    public String getAk() {
        return ak;
    }
    
    public void setAk(String ak) {
        this.ak = ak;
    }
    
    public String getSk() {
        return sk;
    }
    
    public void setSk(String sk) {
        this.sk = sk;
    }
    
}

AccessServiceImpl.java:

package com.cloud.apigateway.sdk.demo;

import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.SSLContext;

import org.apache.http.Header;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import com.cloud.sdk.DefaultRequest;
import com.cloud.sdk.Request;
import com.cloud.sdk.auth.credentials.BasicCredentials;
import com.cloud.sdk.auth.signer.Signer;
import com.cloud.sdk.auth.signer.SignerFactory;
import com.cloud.sdk.http.HttpMethodName;


public class AccessServiceImpl extends AccessService {

 private CloseableHttpClient client = null;

 public AccessServiceImpl(String serviceName, String region, String ak,
   String sk) {
  super(serviceName, region, ak, sk);
 }

 /** {@inheritDoc} */

 public HttpResponse access(URL url, Map<String, String> headers,
   InputStream content, Long contentLength, HttpMethodName httpMethod)
   throws Exception {

  // Make a request for signing.
  Request request = new DefaultRequest(this.serviceName);
  try {
   // Set the request address.
   request.setEndpoint(url.toURI());

   String urlString = url.toString();

   String parameters = null;

    if (urlString.contains("?")) {
        parameters = urlString.substring(urlString.indexOf("?") + 1);
        Map parametersmap = new HashMap<String, String>();
                
        if (null != parameters && !"".equals(parameters)) {
                    String[] parameterarray = parameters.split("&");
                    
                    for (String p : parameterarray) {
                        String key = p.split("=")[0];
                        String value = p.split("=")[1];
                        parametersmap.put(key, value);
                    }
                    request.setParameters(parametersmap);
          }
     }

  } catch (URISyntaxException e) {
   // It is recommended to add logs in this place. 
   e.printStackTrace();
  }
  // Set the request method.
  request.setHttpMethod(httpMethod);
  if (headers != null) {
   // Add request header information if required. 
   request.setHeaders(headers);
  }
  // Configure the request content. 
  request.setContent(content);

  // Select an algorithm for request signing.
  Signer signer = SignerFactory.getSigner(serviceName, region);
  // Sign the request, and the request will change after the signing.
  signer.sign(request, new BasicCredentials(this.ak, this.sk));

  // Make a request that can be sent by the HTTP client.
  HttpRequestBase httpRequestBase = createRequest(url, null,
    request.getContent(), contentLength, httpMethod);
  Map<String, String> requestHeaders = request.getHeaders();
  // Put the header of the signed request to the new request.
  for (String key : requestHeaders.keySet()) {
   if (key.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH.toString())) {
    continue;
   }
   httpRequestBase.addHeader(key, requestHeaders.get(key));
  }

  HttpResponse response = null;
  SSLContext sslContext = SSLContexts.custom()
    .loadTrustMaterial(null, new TrustSelfSignedStrategy())
    .useTLS().build();
  SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
    sslContext, new AllowAllHostnameVerifier());

  client = HttpClients.custom().setSSLSocketFactory(sslSocketFactory)
    .build();
  // Send the request, and a response will be returned.
  response = client.execute(httpRequestBase);
  return response;
 }

 /**
  * Make a request that can be sent by the HTTP client.
  * 
  * @param url
  *            specifies the API access path.
  * @param header
  *            specifies the header information to be added.
  * @param content
  *            specifies the body content to be sent in the API call.
  * @param contentLength
  *            specifies the length of the content. This parameter is optional.
  * @param httpMethod
  *            specifies the HTTP method to be used.
  * @return specifies the request that can be sent by an HTTP client.
  */
 private static HttpRequestBase createRequest(URL url, Header header,
   InputStream content, Long contentLength, HttpMethodName httpMethod) {

  HttpRequestBase httpRequest;
  if (httpMethod == HttpMethodName.POST) {
   HttpPost postMethod = new HttpPost(url.toString());

   if (content != null) {
    InputStreamEntity entity = new InputStreamEntity(content,
      contentLength);
    postMethod.setEntity(entity);
   }
   httpRequest = postMethod;
  } else if (httpMethod == HttpMethodName.PUT) {
   HttpPut putMethod = new HttpPut(url.toString());
   httpRequest = putMethod;

   if (content != null) {
    InputStreamEntity entity = new InputStreamEntity(content,
      contentLength);
    putMethod.setEntity(entity);
   }
  } else if (httpMethod == HttpMethodName.PATCH) {
   HttpPatch patchMethod = new HttpPatch(url.toString());
   httpRequest = patchMethod;

   if (content != null) {
    InputStreamEntity entity = new InputStreamEntity(content,
      contentLength);
    patchMethod.setEntity(entity);
   }
  } else if (httpMethod == HttpMethodName.GET) {
   httpRequest = new HttpGet(url.toString());
  } else if (httpMethod == HttpMethodName.DELETE) {
   httpRequest = new HttpDelete(url.toString());
  } else if (httpMethod == HttpMethodName.HEAD) {
   httpRequest = new HttpHead(url.toString());
  } else {
   throw new RuntimeException("Unknown HTTP method name: "
     + httpMethod);
  }

  httpRequest.addHeader(header);
  return httpRequest;
 }

 @Override
 public void close() {
  try {
   if (client != null) {
    client.close();
   }
  } catch (IOException e) {
   // It is recommended to add logs in this place. 
   e.printStackTrace();
  }
 }

}

Demo.java:

package com.cloud.apigateway.sdk.demo;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.HttpResponse;

import com.cloud.sdk.http.HttpMethodName;


public class Demo {

 //replace real region
 private static final String region = "regionName";

 //replace real service name
 private static final String serviceName = "serviceName";

 public static void main(String[] args) {

  //replace real AK
  String ak = "akString";
  //replace real SK
  String sk = "skString";

  // get method
  //replace real url
  String url = "urlString";
  get(ak, sk, url);

  // post method
  //replace real url
  String postUrl = "urlString";
  //replace real body
  String postbody = "bodyString";
  post(ak, sk, postUrl, postbody);

  // put method
  //replace real body
  String putbody = "bodyString";
  //replace real url
  String putUrl = "urlString";
  put(ak, sk, putUrl, putbody);

  // delete method
  //replace real url
  String deleteUrl = "urlString";
  delete(ak, sk, deleteUrl);
 }

 public static void put(String ak, String sk, String requestUrl,
   String putBody) {

  AccessService accessService = null;
  try {
   accessService = new AccessServiceImpl(serviceName, region, ak, sk);
   URL url = new URL(requestUrl);
   HttpMethodName httpMethod = HttpMethodName.PUT;
   
   InputStream content = new ByteArrayInputStream(putBody.getBytes());
   HttpResponse response = accessService.access(url, content,
     (long) putBody.getBytes().length, httpMethod);
   
   System.out.println(response.getStatusLine().getStatusCode());
   
  
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   accessService.close();
  }

 }
 
 public static void patch(String ak, String sk, String requestUrl,
   String putBody) {

  AccessService accessService = null;
  try {
   accessService = new AccessServiceImpl(serviceName, region, ak, sk);
   URL url = new URL(requestUrl);
   HttpMethodName httpMethod = HttpMethodName.PATCH;
   InputStream content = new ByteArrayInputStream(putBody.getBytes());
   HttpResponse response = accessService.access(url, content,
     (long) putBody.getBytes().length, httpMethod);
   
   System.out.println(convertStreamToString(response.getEntity()
     .getContent()));
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   accessService.close();
  }

 }

 public static void delete(String ak, String sk, String requestUrl) {

  AccessService accessService = null;

  try {
   accessService = new AccessServiceImpl(serviceName, region, ak, sk);
   URL url = new URL(requestUrl);
   HttpMethodName httpMethod = HttpMethodName.DELETE;

   HttpResponse response = accessService.access(url, httpMethod);
   System.out.println(convertStreamToString(response.getEntity()
     .getContent()));
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   accessService.close();
  }

 }

 public static void get(String ak, String sk, String requestUrl) {

  AccessService accessService = null;

  try {
   accessService = new AccessServiceImpl(serviceName, region, ak, sk);
   URL url = new URL(requestUrl);
   HttpMethodName httpMethod = HttpMethodName.GET;
   HttpResponse response;
   response = accessService.access(url, httpMethod);
   System.out.println(convertStreamToString(response.getEntity()
     .getContent()));
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   accessService.close();
  }

 }

 public static void post(String ak, String sk, String requestUrl,
   String postbody) {

  AccessService accessService = new AccessServiceImpl(serviceName,
    region, ak, sk);
  URL url = null;
  try {
   url = new URL(requestUrl);
  } catch (MalformedURLException e) {
   e.printStackTrace();
  }
  InputStream content = new ByteArrayInputStream(postbody.getBytes());
  HttpMethodName httpMethod = HttpMethodName.POST;
  HttpResponse response;

  try {
   response = accessService.access(url, content,
     (long) postbody.getBytes().length, httpMethod);
   System.out.println(convertStreamToString(response.getEntity()
     .getContent()));
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   accessService.close();
  }
 }

 private static String convertStreamToString(InputStream is) {
  BufferedReader reader = new BufferedReader(new InputStreamReader(is));
  StringBuilder sb = new StringBuilder();

  String line = null;
  try {
   while ((line = reader.readLine()) != null) {
    sb.append(line + "\n");
   }
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    is.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }

  return sb.toString();
 }

}
NOTE:
  1. Parameters URIAKSK, and HTTP METHOD are mandatory.
  2. You can use the request.addHeader() method to add header information.
Registration