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

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;
	}

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;
	}

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[] --> String  
	    public static String bytes2String(byte b[]){  
	        String result_str = new String(b);  
	        return result_str;  
	    }  

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

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

  • 0
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值