package com.cloud.common.utils; import com.alibaba.fastjson.JSON; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; /** * Token信息类 * @author * @date */ class Token { public String accessToken; public String tokenType; public String refreshToken; public String expiresIn; public String scope; public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } public String getTokenType() { return tokenType; } public void setTokenType(String tokenType) { this.tokenType = tokenType; } public String getRefreshToken() { return refreshToken; } public void setRefreshToken(String refreshToken) { this.refreshToken = refreshToken; } public String getExpiresIn() { return expiresIn; } public void setExpiresIn(String expiresIn) { this.expiresIn = expiresIn; } public String getScope() { return scope; } public void setScope(String scope) { this.scope = scope; } } /** * 获取登录人的token信息类 * @author * @date */ public class TokenUtil { public static String getAccessToken() { try { HttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost("http://127.0.0.1:8080/api-o/oauth/token"); List params = new ArrayList(2); params.add(new BasicNameValuePair("grant_type", "password")); params.add(new BasicNameValuePair("client_id", "system")); params.add(new BasicNameValuePair("client_secret", "system")); params.add(new BasicNameValuePair("scope", "app")); params.add(new BasicNameValuePair("username", "admin|USERNAME")); params.add(new BasicNameValuePair("password", "admin")); httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); //Execute and get the response. HttpResponse response = httpclient.execute(httppost); String result = EntityUtils.toString(response.getEntity(), "UTF-8"); Token tokens = JSON.parseObject(result, Token.class); return tokens.getAccessToken(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } }