Java获取Token,含Authorization参数以及body参数

代码如下:

public String getAccesstoken () {
		 String result = null;
	        //请求地址
		 Properties pro = getProperties();
			String url = pro.getProperty("getToken");
			String responseInfo = "";
			String appId= "";
			String appSecret = "";
			//body中的参数
			String grant_type = "";
			String scope="";
			//参数设置
	        List<NameValuePair> parameForToken = new ArrayList<NameValuePair>();
	        parameForToken.add(new BasicNameValuePair("grant_type", grant_type));
	        parameForToken.add(new BasicNameValuePair("scope", scope));
       //使用base64进行加密
		byte[] tokenByte = Base64.encodeBase64((appId+":"+appSecret).getBytes());
		//将加密的信息转换为string
		String tokenStr = Base.bytesSub2String(tokenByte, 0, tokenByte.length);
		//Basic YFUDIBGDJHFK78HFJDHF==    token的格式
		String token = "Basic "+tokenStr;
        // 获取httpclient
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            //创建post请求
            HttpPost httpPost = new HttpPost(url);
            //PostMethod pMethod = new PostMethod(url);
             // 设置请求和传输超时时间  
            RequestConfig requestConfig = RequestConfig.custom()  
                    .setSocketTimeout(20000).setConnectTimeout(20000).build();  
            httpPost.setConfig(requestConfig); 
            // 提交参数发送请求
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(parameForToken);
            httpPost.setEntity(urlEncodedFormEntity);
            //把认证信息发到header中
            httpPost.setHeader("Authorization",token);
            response = httpclient.execute(httpPost);
            // 得到响应信息
            int statusCode = response.getStatusLine().getStatusCode();
            // 判断响应信息是否正确
            if (statusCode != HttpStatus.SC_OK) {
                // 终止并抛出异常
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //result = EntityUtils.toString(entity);//不进行编码设置
                result = EntityUtils.toString(entity, "UTF-8");
            }
            EntityUtils.consume(entity);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭所有资源连接
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpclient != null) {
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println(result);
        return result;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80

getProperties()方法:

	public Properties getProperties() {
		InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("resources/constant.properties");    
		Properties p = new Properties();    
		try {    
		   p.load(inputStream);    
		} catch (IOException e1) { 
			System.out.println("读取constant.properties文件失败"+ e1);
		   e1.printStackTrace();    
		} 
		return p;
	}

 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

Base.java中的bytesSub2String()方法:

 /*** 
	      * @input   src         待截取字节数组 
	      *          start       待截取字节数组的开始位置 
	      *          src_size    截取的长度 == 数据类型的长度 
	      *            
	      * @output  String 字节截取转换成String后的结果 
	      *  
	      * **/  
	    public static String bytesSub2String(byte[] src,int start,int src_size) {   
	        byte[] resBytes = new byte[src_size];  
	        System.arraycopy(src, start, resBytes, 0, src_size);   
	     //     System.out.println(" len ==" +resBytes.length   
	     //              + " sub_bytes = " + bytes2Int1(resBytes));   
	        return  bytes2String(resBytes);  
	    }   
  // byte[] --&gt; String  
    public static String bytes2String(byte b[]){  
        String result_str = new String(b);  
        return result_str;  
    }  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

常量全在constant.properties中写着。接下来一般都是把这个写入定时任务中,因为token一般都有有效时间,过了有效时间需要重新申请。所以写入定时任务中,让定时任务执行并获取token。

借鉴:https://blog.csdn.net/mhqyr422/article/details/79787518
http://chenliang1234576.iteye.com/blog/1167833

                                </div>
            <link href='javascript:void(0)'>

Java获取Token,含Authorization参数以及body参数

代码如下:

public String getAccesstoken () {
		 String result = null;
	        //请求地址
		 Properties pro = getProperties();
			String url = pro.getProperty("getToken");
			String responseInfo = "";
			String appId= "";
			String appSecret = "";
			//body中的参数
			String grant_type = "";
			String scope="";
			//参数设置
	        List<NameValuePair> parameForToken = new ArrayList<NameValuePair>();
	        parameForToken.add(new BasicNameValuePair("grant_type", grant_type));
	        parameForToken.add(new BasicNameValuePair("scope", scope));
       //使用base64进行加密
		byte[] tokenByte = Base64.encodeBase64((appId+":"+appSecret).getBytes());
		//将加密的信息转换为string
		String tokenStr = Base.bytesSub2String(tokenByte, 0, tokenByte.length);
		//Basic YFUDIBGDJHFK78HFJDHF==    token的格式
		String token = "Basic "+tokenStr;
        // 获取httpclient
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            //创建post请求
            HttpPost httpPost = new HttpPost(url);
            //PostMethod pMethod = new PostMethod(url);
             // 设置请求和传输超时时间  
            RequestConfig requestConfig = RequestConfig.custom()  
                    .setSocketTimeout(20000).setConnectTimeout(20000).build();  
            httpPost.setConfig(requestConfig); 
            // 提交参数发送请求
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(parameForToken);
            httpPost.setEntity(urlEncodedFormEntity);
            //把认证信息发到header中
            httpPost.setHeader("Authorization",token);
            response = httpclient.execute(httpPost);
            // 得到响应信息
            int statusCode = response.getStatusLine().getStatusCode();
            // 判断响应信息是否正确
            if (statusCode != HttpStatus.SC_OK) {
                // 终止并抛出异常
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //result = EntityUtils.toString(entity);//不进行编码设置
                result = EntityUtils.toString(entity, "UTF-8");
            }
            EntityUtils.consume(entity);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭所有资源连接
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpclient != null) {
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println(result);
        return result;
}