Java 集成 PowerBI RestAPI

需要引入Jar包

<!-- 微软AAD -->
<dependency>
    <groupId>com.microsoft.azure</groupId>
	<artifactId>adal4j</artifactId>
	<version>1.6.0</version>
</dependency>

 

获取嵌入PowerBI的参数

在自定义应用内访问PowerBI,调用JavaScript API的过程中,需要三个参数,分别是

  • embedToken 嵌入令牌,用于鉴权
  • embedURL 报表的URL地址
  • reportId 报表的唯一标志

获取Access Token

public static AuthenticationResult getAccessToken() throws Exception {
		AuthenticationContext context;
		AuthenticationResult result;
		ExecutorService service = null;
		try {
			service = Executors.newFixedThreadPool(1);
            context = new AuthenticationContext("https://login.partner.microsoftonline.cn/common/oauth2/authorize", false, service);
            Future<AuthenticationResult> future = context.acquireToken(
            		"https://analysis.chinacloudapi.cn/powerbi/api", "你的ID", 
            		"你得账户", "你得密码",
                    null);
            result = future.get();
		} finally {
			service.shutdown();
		}
		if (result == null) {
            throw new ServiceUnavailableException(
                    "authentication result was null");
        }
		return result;
	}

获取Embed Token

只有拿到了accessToken才能获取EmbedToken

public static String accessToken(String accessToken,String url){
		CloseableHttpClient httpClient = HttpClients.createDefault();

		String entityStr = null;
		CloseableHttpResponse response = null;
		Map<String, String> map = new HashMap<>();
		map.put("accessLevel", "View");
		try {
			// 创建POST请求对象
			HttpPost httpPost = new HttpPost(url);
			// 传输的类型
//			httpPost.addHeader("Content-Type", "text/plain");
			httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
			httpPost.addHeader("Authorization", "Bearer " + accessToken);
			httpPost.addHeader("Cache-Control", "max-age=0");
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			if (map != null) {
				for (Entry<String, String> entry : map.entrySet()) {
					nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
				}
			}
			// 设置参数到请求对象中
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
			// 执行请求
			response = httpClient.execute(httpPost);
			// 获得响应的实体对象
			HttpEntity entity = response.getEntity();
			// 使用Apache提供的工具类进行转换成字符串
			entityStr = EntityUtils.toString(entity, "UTF-8");

		} catch (ClientProtocolException e) {
			System.err.println("Http协议出现问题");
			e.printStackTrace();
		} catch (ParseException e) {
			System.err.println("解析错误");
			e.printStackTrace();
		} catch (IOException e) {
			System.err.println("IO异常");
			e.printStackTrace();
		} finally {
			// 释放连接
			if (null != response) {
				try {
					response.close();
					httpClient.close();
				} catch (IOException e) {
					System.err.println("释放连接出错");
					e.printStackTrace();
				}
			}
		}

		return entityStr;
	}

获取报表信息

public static String geturl(String geturl,String accessToken) throws Exception{
		URL url = new URL(geturl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setRequestMethod("GET");
        conn.setRequestProperty("Authorization", "Bearer " + accessToken);
        conn.setRequestProperty("Accept","application/json");

        int httpResponseCode = conn.getResponseCode();
        if(httpResponseCode == 200) {
            BufferedReader in = null;
            StringBuilder response;
            try{
                in = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
                String inputLine;
                response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
            } finally {
                in.close();
            }
            return response.toString();
        } else {
            return String.format("Connection returned HTTP code: %s with message: %s",
                    httpResponseCode, conn.getResponseMessage());
        }
	}

JS - 调用PowerBI 

https://github.com/Microsoft/PowerBI-JavaScript/releases下载最新的release,在dist目录找到powerbi.js文件

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="static/powerbi.js"></script>
<title>Insert title here</title>
</head>
<body>

	<div id="reportContainer" style="width: 100%; height: px"></div>
</body>
<script>
setSize();
window.onresize = function(){
	setSize();
}
function setSize(){
	var windowHeight = document.documentElement.clientHeight || document.body.clientHeight
	console.log(windowHeight)
	document.getElementById('reportContainer').style.height = windowHeight - 16+"px";
	
}
	var accessToken =  "H4sIAAAAAAAEAB1WNa**********8xrhvsfmv_v_wFxu9FBLgwAAA==";
    var embedUrl = "https://app.powerbi.cn/reportEmbed?reportId=******";
    var reportId = "*******";
    
	
		var models = window['powerbi-client'].models;
		var permissions = models.Permissions.All;
	    var config= {
	        type: 'report',
	        tokenType:  models.TokenType.Embed,
	        accessToken: accessToken,
	        embedUrl: embedUrl,
	        id: reportId,
	        permissions: permissions,
	        settings: {
	            filterPaneEnabled: true,
	            navContentPaneEnabled: true
	        }
	    }
    var reportContainer =  document.getElementById('reportContainer');	
    var report = powerbi.embed(reportContainer, config);
	

    </script>
</html>

 

 

  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值