环境准备 确保鸿蒙开发环境已配置完成,包括DevEco Studio和SDK。注册百度AI开放平台账号,创建应用并获取API Key和Secret Key。

依赖配置 在鸿蒙项目的build.gradle中添加百度AI的HTTP请求依赖:

implementation 'com.squareup.okhttp3:okhttp:4.9.1'
implementation 'com.google.code.gson:gson:2.8.6'

百度AI鉴权实现

获取Access Token 调用百度OAuth接口获取临时token,需替换API_KEYSECRET_KEY为实际值:

String authUrl = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials" +
                 "&client_id=" + API_KEY + 
                 "&client_secret=" + SECRET_KEY;

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(authUrl).build();
Response response = client.newCall(request).execute();
String responseData = response.body().string();
JsonObject jsonObject = JsonParser.parseString(responseData).getAsJsonObject();
String accessToken = jsonObject.get("access_token").getAsString();

情感分析API调用

构建请求参数 将待分析文本进行URL编码,注意单次请求不超过1024字节:

String text = "今天天气真好";
String encodedText = URLEncoder.encode(text, "UTF-8");
String url = "https://aip.baidubce.com/rpc/2.0/nlp/v1/sentiment_classify?access_token=" + accessToken;

String jsonBody = "{\"text\":\"" + text + "\"}";
RequestBody body = RequestBody.create(jsonBody, MediaType.get("application/json"));

处理API响应 解析返回的JSON数据,提取情感极性(0消极/1中性/2积极)和置信度:

Request apiRequest = new Request.Builder()
    .url(url)
    .post(body)
    .build();
Response apiResponse = client.newCall(apiRequest).execute();
String result = apiResponse.body().string();

JsonObject resultJson = JsonParser.parseString(result).getAsJsonObject();
JsonArray items = resultJson.getAsJsonArray("items");
JsonObject sentiment = items.get(0).getAsJsonObject();
int sentimentType = sentiment.get("sentiment").getAsInt();
double confidence = sentiment.get("confidence").getAsDouble();

鸿蒙UI集成示例

前端界面设计ability_main.xml中添加文本输入框和结果显示组件:

<TextField
    ohos:id="$+id:input_text"
    ohos:width="match_parent"
    ohos:height="50vp"
    ohos:hint="输入待分析文本"/>

<Button
    ohos:id="$+id:analyze_btn"
    ohos:text="分析情感"
    ohos:width="150vp"
    ohos:height="50vp"/>

<Text
    ohos:id="$+id:result_text"
    ohos:width="match_parent"
    ohos:height="100vp"/>

事件绑定处理MainAbilitySlice.java中实现按钮点击事件:

TextField inputText = (TextField) findComponentById(ResourceTable.Id_input_text);
Button analyzeBtn = (Button) findComponentById(ResourceTable.Id_analyze_btn);
Text resultText = (Text) findComponentById(ResourceTable.Id_result_text);

analyzeBtn.setClickedListener(component -> {
    String text = inputText.getText();
    new Thread(() -> {
        String result = analyzeSentiment(text);
        getUITaskDispatcher().asyncDispatch(() -> {
            resultText.setText(result);
        });
    }).start();
});

错误处理与优化

网络异常处理 增加网络请求超时和重试机制:

OkHttpClient client = new OkHttpClient.Builder()
    .connectTimeout(10, TimeUnit.SECONDS)
    .readTimeout(30, TimeUnit.SECONDS)
    .retryOnConnectionFailure(true)
    .build();

结果缓存策略 使用鸿蒙的Preferences实现本地缓存:

Preferences preferences = Preferences.getDefaultPreferences(getContext());
preferences.putString("last_token", accessToken);
preferences.putLong("token_expire", System.currentTimeMillis() + 86400000);

完整流程说明

  1. 用户在前端输入待分析文本
  2. 系统自动获取有效的百度AI访问令牌
  3. 调用情感分析API并处理返回结果
  4. 将分析结果(积极/中性/消极)及置信度展示给用户
  5. 自动处理网络异常和令牌过期情况

注意实际部署时需要处理敏感信息加密存储,建议将API密钥存储在鸿蒙的config.json中并通过环境变量注入。百度AI情感分析API每日有免费调用限额,超过后会产生费用。

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐