本实例通过脚本实现获取并打印 token。
1、将账号密码 BASE64 编码
2、设置请求头
3、读取返回数据
4、处理返回的 json 格式数据后打印 token
1.导入httpclient.jar包
2.导入gson.jar包
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());
//将账号密码BASE64编码
get = new HttpGet("http://localhost:8090/TotalControl/v1/login");
get.setHeader("Authorization", encode);
//设置请求头
response = client.execute(get);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String re=in.readLine();
//读取返回数据
in.close();
Gson json=new Gson();
JsonObject jsonObject=json.fromJson(re, JsonObject.class);
System.out.println(jsonObject.get("value").getAsJsonObject().get("token").getAsString());
//处理返回的json格式数据后打印token
}
}