Get and print token

This example uses a script to get and print tokens.

Programming language: Java

Steps

1. Encode the account password BASE64

2. Set request header

3. Read return data

4. Print token after processing returned json format data

Source code

1. Import the httpclient.jar package
2. Import gson.jar package

package devices;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;


import com.google.gson.Gson;
import com.google.gson.JsonObject;


public class token {
public static final String deviceId = "device@32463010";
public static HttpClient client = HttpClients.createDefault();
public static JsonObject jsonObj = new JsonObject();
public static BufferedReader in = null;
public static HttpResponse response = null;
public static HttpGet get = null;
public static HttpPost post = null;
public static StringEntity entity = null;
public static void main(String[] args) throws ClientProtocolException, IOException {
String encode=Base64.encodeBase64String("sigma:jiehua".getBytes());
                //Encode the account password BASE64
get = new HttpGet("http://localhost:8090/TotalControl/v1/login");              
get.setHeader("Authorization", encode);
                //Set request header
response = client.execute(get);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String re=in.readLine();
                //Read return data
in.close();
Gson json=new Gson();
JsonObject jsonObject=json.fromJson(re, JsonObject.class);
System.out.println(jsonObject.get("value").getAsJsonObject().get("token").getAsString()); 
                //Print token after processing returned json format data
}
}