Java

package io.lingk.sampleclient;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Clock;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class SampleClient {

    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, IOException {
        String endpoint = "https://www.lingkapis.com/v1/@self/ps/students";

        String keyId = "[your key]";
        String secret64 = "[your secret]";
        byte[] secret = secret64.getBytes();

        URL url = new URL(endpoint);
        String requestMethod = "GET";  // GET, POST, PUT, DELETE

        // get current time in UTC
        ZonedDateTime nowInUtc = ZonedDateTime.now(Clock.systemUTC());
        String formattedDate = nowInUtc.format(DateTimeFormatter.RFC_1123_DATE_TIME);

        // create a signing string to sign
        String signingString = "date: " + formattedDate + "\n(request-target): " + requestMethod.toLowerCase() + " " + url.getPath();

        // sign the signing string
        SecretKeySpec sks = new SecretKeySpec(secret, "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(sks);

        byte[] hmac = mac.doFinal(signingString.getBytes());
        String encodedHMAC = URLEncoder.encode(Base64.getEncoder().encodeToString(hmac), "ASCII");

        // construct authorization header
        String authorizationHeader = "Signature keyId=\"" + keyId + "\",headers=\"date (request-target)\",algorithm=\"hmac-sha1\",signature=\"" + encodedHMAC + "\"";

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(endpoint);
        httpGet.addHeader("Date", formattedDate);
        httpGet.addHeader("Authorization", authorizationHeader);
        CloseableHttpResponse response1 = httpclient.execute(httpGet);
        try {
             System.out.println(response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();
            InputStream is = entity1.getContent();
            String theString = IOUtils.toString(is, "ASCII"); 
            System.out.println(theString);
            EntityUtils.consume(entity1);
        } finally {
            response1.close();
        }
    }

}

Last updated