HttpClient获取Token

296 阅读1分钟

按账户授权的token,直接贴代码了

import org.apache.commons.httpclient.HttpClient;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class WebHttpClient{

    public String getToken(){
        String token;
        InputStream inputStream = null;
        String requestUrl = "127.0.0.1:8080/oauth/token";
        try {
            HttpClient httpClient = new HttpClient();
            PostMethod postMethod = new PostMethod(requestUrl);
            postMethod.addParameter("client_id", "user00004");
            postMethod.addParameter("client_secret", "ddb454545");
            postMethod.addParameter("grant_type", "client_credentials");
            //127.0.0.1:8080/oauth/token?client_id=user00004&client_secret=ddb454545&grant_type=client_credentials
            httpClient.executeMethod(postMethod);// 执行请求
            inputStream =  postMethod.getResponseBodyAsStream();// 获取返回的流
            BufferedReader br;
            StringBuffer buffer = new StringBuffer();
            // 将返回的输入流转换成字符串
            br = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
            }
            log.error("获取token接口内容为:{}" , buffer);
            //只要里面的access_token值
            token = JSONObject.parseObject(buffer.toString()).getString("access_token");
        }catch (Exception e) {
            log.error("请求异常:{}" ,e.getMessage());
            throw new RuntimeException(e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return token;
    }
}