You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求协助:通过Android应用向Power BI流式数据集推送CPU、RAM数据

可行实现方案:Android 推送数据到 Power BI 流式数据集

先做必查的前置验证,很多推送失败都是基础配置问题:

  • 确认推送端点 URL 正确:格式为 https://api.powerbi.com/v1.0/myorg/datasets/{DATASET_ID}/rows?key={ACCESS_KEY},替换 {DATASET_ID} 和 {ACCESS_KEY},注意密钥是流式数据集专属的推送密钥,不是 Power BI 账号密钥。
  • 匹配数据集字段:请求体的字段名、数据类型必须和 Power BI 流式数据集定义完全一致(大小写敏感),比如数据集定义了 Timestamp(DateTime 类型)、CPU(Number)、RAM(Number),请求体里的键名、类型不能错。
  • 确保应用有网络权限:在 AndroidManifest.xml 中添加 <uses-permission android:name="android.permission.INTERNET" />。

方案一:Volley 实现

如果之前用 Volley 失败,大概率是请求头或请求体格式错误,以下是完整可运行代码:

1. 添加依赖

在模块级 build.gradle 中加入:

implementation 'com.android.volley:volley:1.2.1'
implementation 'com.google.code.gson:gson:2.10.1'

2. 数据模型类

public class PowerBiMetrics {
    public String Timestamp;
    public double CPU;
    public double RAM;

    public PowerBiMetrics(String timestamp, double cpu, double ram) {
        Timestamp = timestamp;
        CPU = cpu;
        RAM = ram;
    }
}

3. 推送代码

String PUSH_ENDPOINT = "你的 Power BI 推送 URL";
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());

// 构造推送数据(注意是数组格式,Power BI 要求接收数组)
List<PowerBiMetrics> metricsList = new ArrayList<>();
metricsList.add(new PowerBiMetrics(
    new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US).format(new Date()),
    42.6, // 替换为实际 CPU 使用率
    58.3  // 替换为实际 RAM 使用率
));

String requestBody = new Gson().toJson(metricsList);

StringRequest pushRequest = new StringRequest(Request.Method.POST, PUSH_ENDPOINT,
    response -> Log.d("PowerBI", "推送成功: " + response),
    error -> {
        Log.e("PowerBI", "推送失败", error);
        if (error.networkResponse != null) {
            Log.e("PowerBI", "错误码: " + error.networkResponse.statusCode);
            Log.e("PowerBI", "错误详情: " + new String(error.networkResponse.data));
        }
    }) {
    @Override
    public String getBodyContentType() {
        return "application/json; charset=utf-8";
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        try {
            return requestBody.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            VolleyLog.wtf("编码失败", e);
            return null;
        }
    }
};

queue.add(pushRequest);

方案二:Retrofit 实现

如果之前 Retrofit 报错,检查接口定义和转换器配置:

1. 添加依赖

implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

2. 定义 API 接口

public interface PowerBiApi {
    @POST("datasets/{datasetId}/rows?key={accessKey}")
    Call<Void> pushMetrics(
        @Path("datasetId") String datasetId,
        @Path("accessKey") String accessKey,
        @Body List<PowerBiMetrics> metricsList
    );
}

3. 发起推送请求

// 初始化 Retrofit
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.powerbi.com/v1.0/myorg/")
    .addConverterFactory(GsonConverterFactory.create())
    .build();

PowerBiApi api = retrofit.create(PowerBiApi.class);

// 构造数据
List<PowerBiMetrics> metricsList = new ArrayList<>();
metricsList.add(new PowerBiMetrics(
    new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US).format(new Date()),
    42.6,
    58.3
));

// 发起请求
Call<Void> call = api.pushMetrics("你的数据集ID", "你的推送密钥", metricsList);
call.enqueue(new Callback<Void>() {
    @Override
    public void onResponse(Call<Void> call, Response<Void> response) {
        if (response.isSuccessful()) {
            Log.d("PowerBI", "推送成功");
        } else {
            Log.e("PowerBI", "失败,错误码: " + response.code());
            try {
                Log.e("PowerBI", "错误信息: " + response.errorBody().string());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onFailure(Call<Void> call, Throwable t) {
        Log.e("PowerBI", "请求异常", t);
    }
});

方案三:原生 HttpURLConnection 实现

如果第三方库有兼容问题,用原生代码排查:

new Thread(() -> {
    try {
        URL url = new URL("你的 Power BI 推送 URL");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        conn.setDoOutput(true);

        // 构造请求体
        List<PowerBiMetrics> metricsList = new ArrayList<>();
        metricsList.add(new PowerBiMetrics(
            new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US).format(new Date()),
            42.6,
            58.3
        ));
        String requestBody = new Gson().toJson(metricsList);

        // 写入请求体
        OutputStream os = conn.getOutputStream();
        os.write(requestBody.getBytes("utf-8"));
        os.flush();
        os.close();

        // 处理响应
        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            Log.d("PowerBI", "推送成功");
        } else {
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) sb.append(line);
            br.close();
            Log.e("PowerBI", "失败,错误码: " + responseCode + ",详情: " + sb.toString());
        }
        conn.disconnect();
    } catch (Exception e) {
        Log.e("PowerBI", "请求失败", e);
    }
}).start();

常见错误排查

  • 字段不匹配:返回 The request body is invalid,检查数据集字段名和请求体键名的大小写、拼写是否完全一致。
  • 时间格式错误:DateTime 字段必须用 ISO 8601 格式(如 2024-05-20T14:30:00Z),不能用其他格式。
  • 密钥错误:返回 401/403,确认使用的是流式数据集的推送密钥(在 Power BI 数据集的「推送数据」选项中获取),而非工作区密钥。
  • 请求体格式错误:必须用 JSON 数组包裹数据,即使单条数据也要写成 [{...}],不能直接传单个对象。

内容的提问来源于stack exchange,提问作者Pint-Real-Spin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 19:30:55