如何将一个JavaEE的SDK依赖到Android中

news2024/11/15 13:49:16

1. 前言

最近有个需求,需要集成阿里的一个SDK : 通义听悟,但是这个SDK是专门给WebJavaEE使用的,所以导致接入后,运行报错,有兼容性问题,该如何解决,使其能在Android中正常运行呢 ?

2. 添加Maven依赖

首先添加Maven依赖

implementation(
    group = "com.aliyun",
    name = "aliyun-java-sdk-core",
    version = "4.6.0"
)
implementation(
    group = "com.alibaba",
    name = "fastjson",
    version = "1.2.83"
)

这个时候会提示报错,有资源冲突

Execution failed for task ':app:mergeDebugJavaResource'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.MergeJavaResWorkAction
   > 2 files found with path 'META-INF/DEPENDENCIES' from inputs:
      - C:\Users\Haokai.Zhu\.gradle\caches\modules-2\files-2.1\org.apache.httpcomponents\httpclient\4.5.13\e5f6cae5ca7ecaac1ec2827a9e2d65ae2869cada\httpclient-4.5.13.jar
      - C:\Users\Haokai.Zhu\.gradle\caches\modules-2\files-2.1\org.apache.httpcomponents\httpcore\4.4.15\7f2e0c573eaa7a74bac2e89b359e1f73d92a0a1d\httpcore-4.4.15.jar
     Adding a packaging block may help, please refer to
     https://developer.android.com/reference/tools/gradle-api/8.3/com/android/build/api/dsl/Packaging
     for more information

接着我们解决这个冲突,在build.gradleandroid闭包下,添加如下配置

packaging {
    resources {
        excludes += "/META-INF/{AL2.0,LGPL2.1}"
        excludes += "META-INF/DEPENDENCIES"
        excludes += "META-INF/LICENSE.md"
        excludes += "META-INF/NOTICE.md"
        excludes += "META-INF/INDEX.LIST"
        excludes += "META-INF/io.netty.versions.properties"
    }
}

这个时候再重新编译运行,可以发现,可以正常运行到手机上了。

3. 音视频文件离线转写

接着,我们借助阿里听悟SDK的能力,将完整的音频文件转写记录为文本。
具体代码如下

public class TranscriptionTest {

    public void testFiletrans() throws ClientException {
        CommonRequest request = createCommonRequest("tingwu.cn-beijing.aliyuncs.com", "2023-09-30", ProtocolType.HTTPS, MethodType.PUT, "/openapi/tingwu/v2/tasks");
        request.putQueryParameter("type", "offline");

        JSONObject root = new JSONObject();
        root.put("AppKey", Constants.AppKey);

        JSONObject input = new JSONObject();
        //input.fluentPut("FileUrl", "输入待测试的音频url链接")
        input.fluentPut("FileUrl", "https://www.cambridgeenglish.org/images/153149-movers-sample-listening-test-vol2.mp3")
                .fluentPut("SourceLanguage", "en")
                .fluentPut("TaskKey", "task" + System.currentTimeMillis());
        root.put("Input", input);

        JSONObject parameters = new JSONObject();
        JSONObject transcription = new JSONObject();
        transcription.put("DiarizationEnabled", true);
        JSONObject speakerCount = new JSONObject();
        speakerCount.put("SpeakerCount", 2);
        transcription.put("Diarization", speakerCount);
        parameters.put("Transcription", transcription);
        root.put("Parameters", parameters);
        System.out.println(root.toJSONString());
        request.setHttpContent(root.toJSONString().getBytes(), "utf-8", FormatType.JSON);

        DefaultProfile profile = DefaultProfile.getProfile("cn-beijing", Constants.AccessKeyId, Constants.AccessKeyPassword);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonResponse response = client.getCommonResponse(request);
        System.out.println(response.getData());
    }
    public static CommonRequest createCommonRequest(String domain, String version, ProtocolType protocolType, MethodType method, String uri) {
        // 创建API请求并设置参数
        CommonRequest request = new CommonRequest();
        request.setSysDomain(domain);
        request.setSysVersion(version);
        request.setSysProtocol(protocolType);
        request.setSysMethod(method);
        request.setSysUriPattern(uri);
        request.setHttpContentType(FormatType.JSON);
        return request;
    }
}

然后再Activity里调用

binding.btnTest1.setOnClickListener {
    TranscriptionTest().testFiletrans()
}

运行程序,发现报错 : java.lang.NoSuchFieldError: No static field INSTANCE of type Lorg/apache/http/conn/ssl/AllowAllHostnameVerifier

Process: com.heiko.alitingwu, PID: 5944
java.lang.NoSuchFieldError: No static field INSTANCE of type Lorg/apache/http/conn/ssl/AllowAllHostnameVerifier; in class Lorg/apache/http/conn/ssl/AllowAllHostnameVerifier; or its superclasses (declaration of 'org.apache.http.conn.ssl.AllowAllHostnameVerifier' appears in /system/framework/framework.jar!classes5.dex)
	at org.apache.http.conn.ssl.SSLConnectionSocketFactory.<clinit>(SSLConnectionSocketFactory.java:151)
	at com.aliyuncs.http.clients.ApacheHttpClient.createSSLConnectionSocketFactory(ApacheHttpClient.java:123)
	at com.aliyuncs.http.clients.ApacheHttpClient.initConnectionManager(ApacheHttpClient.java:146)
	at com.aliyuncs.http.clients.ApacheHttpClient.init(ApacheHttpClient.java:199)
	at com.aliyuncs.http.HttpClientFactory.buildClient(HttpClientFactory.java:41)
	at com.aliyuncs.DefaultAcsClient.<init>(DefaultAcsClient.java:88)
	at com.aliyuncs.DefaultAcsClient.<init>(DefaultAcsClient.java:77)
	at com.heiko.alitingwu.TranscriptionTest.testFiletrans(TranscriptionTest.java:45)
	at com.heiko.alitingwu.MainActivity.onCreate$lambda$1(MainActivity.kt:25)
	at com.heiko.alitingwu.MainActivity.$r8$lambda$brY7-m4iUte_gFeK6bCl_RDuPSw(Unknown Source:0)
	at com.heiko.alitingwu.MainActivity$$ExternalSyntheticLambda1.onClick(D8$$SyntheticClass:0)
	at android.view.View.performClick(View.java:7741)
	at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1218)
	at android.view.View.performClickInternal(View.java:7711)
	at android.view.View.-$$Nest$mperformClickInternal(Unknown Source:0)
	at android.view.View$PerformClick.run(View.java:30620)
	at android.os.Handler.handleCallback(Handler.java:958)
	at android.os.Handler.dispatchMessage(Handler.java:99)
	at android.os.Looper.loopOnce(Looper.java:257)
	at android.os.Looper.loop(Looper.java:368)
	at android.app.ActivityThread.main(ActivityThread.java:8826)
	at java.lang.reflect.Method.invoke(Native Method)
	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:572)
	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1049)

找不到org/apache/http/conn/ssl/AllowAllHostnameVerifier这个类 ?
依稀记得老版本的Android里,是将ApacheHttpClient给移除掉的,所以这里会找不到相关的类。

那要怎么办呢 ?

其实网上很多文章写的已经很明白了 : https://blog.csdn.net/divaid/article/details/121154062。
要用cz.msebera.android:httpclient:4.5.8这个库来替换ApacheHttpClient,并将相关的引用也一并做修改。
但是阿里听悟的aliyun-java-sdk-core这个SDK是已经封装好的,需要怎样才能将ApacheHttpClient修改为cz.msebera.android:httpclient呢 ?

4. 实现自己的aliyun-java-sdk-core

4.1 复制代码

好在aliyun-java-sdk-core这个库没有做混淆。我们直接将aliyun-java-sdk-core SDK里面的代码复制到我们自己的项目中

在这里插入图片描述

4.2 引用需要的maven依赖

接着我们查看pom.xml文件,将需要的maven依赖改为gradle依赖,添加到我们的Android项目中

在这里插入图片描述
这里值得注意的是,可以使用ChatGPT来帮助我们节省这个重复性工作。

在这里插入图片描述
最终需要添加的Maven依赖如下

	// Gson 依赖
    implementation("com.google.code.gson:gson:2.8.9")

    // Apache HttpClient 依赖
    implementation("org.apache.httpcomponents:httpclient:4.5.13")
    // Apache HttpCore 依赖
    implementation("org.apache.httpcomponents:httpcore:4.4.15")

    // Commons Logging 依赖
    implementation("commons-logging:commons-logging:1.2")

    // Apache Commons Lang3 依赖
    implementation("org.apache.commons:commons-lang3:3.5")

    // JAXB API 依赖
    implementation("javax.xml.bind:jaxb-api:2.3.1") //2.4.0

    // JAXB Runtime 依赖
    implementation("org.glassfish.jaxb:jaxb-runtime:3.0.2")

    // Bouncy Castle 依赖
    implementation("org.bouncycastle:bcprov-jdk15on:1.70")

    // Mockito 依赖
    //testImplementation("org.mockito:mockito-core:${mockito.version}")

    // PowerMock 依赖
    //testImplementation("org.powermock:powermock-core:${powermock.version}")
    //testImplementation("org.powermock:powermock-reflect:${powermock.version}")

    // PowerMock 依赖
    //testImplementation("org.powermock:powermock-module-junit4:${powermock.version}")
    //testImplementation("org.powermock:powermock-api-mockito2:${powermock.version}")

    // JaCoCo 依赖
    //jacocoAgent("org.jacoco:org.jacoco.agent:0.8.7:runtime")

    // Lombok 依赖
    annotationProcessor("org.projectlombok:lombok:1.18.22")
    kapt("org.projectlombok:lombok:1.18.22") // 如果你使用的是 Kotlin,则需要使用 kapt 替代 annotationProcessor
    //providedCompileOnly("org.projectlombok:lombok:1.18.22")
    compileOnly("org.projectlombok:lombok:1.18.22")

    // INI4J 依赖
    implementation("org.ini4j:ini4j:0.5.4")

    // SLF4J 依赖
    implementation("org.slf4j:slf4j-api:1.7.32")
    testImplementation("org.slf4j:slf4j-simple:1.7.32")

    // OpenTracing 依赖
    implementation("io.opentracing:opentracing-api:0.33.0")
    implementation("io.opentracing:opentracing-util:0.33.0")

删除原本的aliyun-java-sdk-core依赖

implementation(
    group = "com.aliyun",
    name = "aliyun-java-sdk-core",
    version = "4.6.0"
)

接着编译运行,可以发现依然会报NoSuchFieldError的错误,但是这时候我们就可以去修改相关代码了。

4.3 使用cz.msebera.android:httpclient

接着将httpClient修改为cz.msebera.android:httpclient

//implementation("org.apache.httpcomponents:httpclient-android:4.3.5")
// 如果还需要httpcore的话
//implementation("org.apache.httpcomponents:httpcore:4.4.15")
implementation("cz.msebera.android:httpclient:4.5.8")

接着Sync下项目,把包引用中的org.apache.http.client修改为cz.msebera.android.httpclient

比如

//import org.apache.http.client.CredentialsProvider;
修改为
import cz.msebera.android.httpclient.client.CredentialsProvider;

注意这里LogUnit用到了自动生成getsetlombok框架,我们这里改用手动生成get、set

4.4 依旧报错 : 找不到ManagementFactory

接着运行,会报错java.lang.management.ManagementFactory不存在

E:\WorkSpace\Android\Ali\AliTingWu\app\src\main\java\com\aliyuncs\utils\LogUtils.java:107: 错误: 程序包java.lang.management不存在
                java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
                                    ^

我们来看一下这里的代码

public static long getCurrentPID() {
    String processName =
            java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
    return Long.parseLong(processName.split("@")[0]);
}

可以发现,这里是获取进程ID,这里可以改成获取Android的进程ID,或者直接图省事写死

public static long getCurrentPID() {
    String processName = "myPID";
    return Long.parseLong(processName.split("@")[0]);
}

4.5 依旧报错 : 无法访问XMLEventReader

接着运行,会发现报这个错 :

E:\WorkSpace\Android\Ali\AliTingWu\app\src\main\java\com\aliyuncs\unmarshaller\XmlUnmashaller.java:18: 错误: 无法访问XMLEventReader
            return (T) unmarshaller.unmarshal(new StringReader(content));
                                   ^
  找不到javax.xml.stream.XMLEventReader的类文件

来看下XmlUnmashaller这个类

public class XmlUnmashaller implements Unmarshaller {

    @Override
    public <T extends AcsResponse> T unmarshal(Class<T> clazz, String content) throws ClientException {
        try {
            JAXBContext jc = JAXBContext.newInstance(clazz);
            javax.xml.bind.Unmarshaller unmarshaller = jc.createUnmarshaller();
            return (T) unmarshaller.unmarshal(new StringReader(content));
        } catch (JAXBException e) {
            throw newUnmarshalException(clazz, content, e);
        }
    }

    private ClientException newUnmarshalException(Class<?> clazz, String xmlContent, Exception e) {
        return new ClientException("SDK.UnmarshalFailed",
                "unmarshal response from xml content failed, clazz = " + clazz.getSimpleName() + ", origin response = " + xmlContent, e);
    }
}

接着往上看,XmlUnmashaller是在哪里调用的 ?
可以发现UnmarshallerFactory中,会去创建XmlUnmashaller

public class UnmarshallerFactory {

    public static Unmarshaller getUnmarshaller(FormatType format) throws IllegalStateException {
        switch (format) {
            case JSON:
                return new JsonUnmashaller();
            case XML:
                return new XmlUnmashaller();
            default:
                throw new IllegalStateException("Unsupported response format: " + format);
        }
    }
}

由于我们这里明确会使用Json,所以Xml相关的代码可以注释掉

public class UnmarshallerFactory {

    public static Unmarshaller getUnmarshaller(FormatType format) throws IllegalStateException {
        switch (format) {
            case JSON:
                return new JsonUnmashaller();
            /*case XML:
                return new XmlUnmashaller();*/
            default:
                throw new IllegalStateException("Unsupported response format: " + format);
        }
    }
}

/*public class XmlUnmashaller implements Unmarshaller {

    @Override
    public <T extends AcsResponse> T unmarshal(Class<T> clazz, String content) throws ClientException {
        try {
            JAXBContext jc = JAXBContext.newInstance(clazz);
            javax.xml.bind.Unmarshaller unmarshaller = jc.createUnmarshaller();
            return (T) unmarshaller.unmarshal(new StringReader(content));
        } catch (JAXBException e) {
            throw newUnmarshalException(clazz, content, e);
        }
    }

    private ClientException newUnmarshalException(Class<?> clazz, String xmlContent, Exception e) {
        return new ClientException("SDK.UnmarshalFailed",
                "unmarshal response from xml content failed, clazz = " + clazz.getSimpleName() + ", origin response = " + xmlContent, e);
    }
}*/

4.6 依旧报错 : 未找到project.properties

接着编译运行,可以发现运行成功了。
但是在执行的时候,却又报了错 : NullPointerException: Attempt to invoke virtual method 'int java.io.Reader.read(char[])'

Process: com.heiko.alitingwu, PID: 4103
	java.lang.ExceptionInInitializerError
		at com.aliyuncs.DefaultAcsClient.<init>(DefaultAcsClient.java:80)
		at com.aliyuncs.DefaultAcsClient.<init>(DefaultAcsClient.java:105)
		at com.heiko.alitingwu.TranscriptionTest.testFiletrans(TranscriptionTest.java:45)
		at com.heiko.alitingwu.MainActivity.onCreate$lambda$1(MainActivity.kt:25)
		at com.heiko.alitingwu.MainActivity.$r8$lambda$brY7-m4iUte_gFeK6bCl_RDuPSw(Unknown Source:0)
		at com.heiko.alitingwu.MainActivity$$ExternalSyntheticLambda1.onClick(D8$$SyntheticClass:0)
		at android.view.View.performClick(View.java:7741)
		at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1218)
		at android.view.View.performClickInternal(View.java:7711)
		at android.view.View.-$$Nest$mperformClickInternal(Unknown Source:0)
		at android.view.View$PerformClick.run(View.java:30620)
		at android.os.Handler.handleCallback(Handler.java:958)
		at android.os.Handler.dispatchMessage(Handler.java:99)
		at android.os.Looper.loopOnce(Looper.java:257)
		at android.os.Looper.loop(Looper.java:368)
		at android.app.ActivityThread.main(ActivityThread.java:8826)
		at java.lang.reflect.Method.invoke(Native Method)
		at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:572)
		at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1049)
	Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.io.Reader.read(char[])' on a null object reference
		at java.util.Properties$LineReader.readLine(Properties.java:434)
		at java.util.Properties.load0(Properties.java:349)
		at java.util.Properties.load(Properties.java:337)
		at com.aliyuncs.http.UserAgentConfig.<clinit>(UserAgentConfig.java:20)
		at com.aliyuncs.DefaultAcsClient.<init>(DefaultAcsClient.java:80) 
		at com.aliyuncs.DefaultAcsClient.<init>(DefaultAcsClient.java:105) 
		at com.heiko.alitingwu.TranscriptionTest.testFiletrans(TranscriptionTest.java:45) 
		at com.heiko.alitingwu.MainActivity.onCreate$lambda$1(MainActivity.kt:25) 
		at com.heiko.alitingwu.MainActivity.$r8$lambda$brY7-m4iUte_gFeK6bCl_RDuPSw(Unknown Source:0) 
		at com.heiko.alitingwu.MainActivity$$ExternalSyntheticLambda1.onClick(D8$$SyntheticClass:0) 
		at android.view.View.performClick(View.java:7741) 
		at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1218) 
		at android.view.View.performClickInternal(View.java:7711) 
		at android.view.View.-$$Nest$mperformClickInternal(Unknown Source:0) 
		at android.view.View$PerformClick.run(View.java:30620) 
		at android.os.Handler.handleCallback(Handler.java:958) 
		at android.os.Handler.dispatchMessage(Handler.java:99) 
		at android.os.Looper.loopOnce(Looper.java:257) 
		at android.os.Looper.loop(Looper.java:368) 
		at android.app.ActivityThread.main(ActivityThread.java:8826) 
		at java.lang.reflect.Method.invoke(Native Method) 
		at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:572) 
		at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1049) 

我们定位到UserAgentConfigprops.load(UserAgentConfig.class.getClassLoader().getResourceAsStream("project.properties"));这行代码

static {
    Properties sysProps = System.getProperties();
    String coreVersion = "";
    Properties props = new Properties();
    try {
        props.load(UserAgentConfig.class.getClassLoader().getResourceAsStream("project.properties"));
        coreVersion = props.getProperty("sdk.project.version");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    DEFAULT_MESSAGE = String.format("AlibabaCloud (%s; %s) Java/%s %s/%s", sysProps.getProperty("os.name"), sysProps
            .getProperty("os.arch"), sysProps.getProperty("java.runtime.version"), "Core", coreVersion);
}

可以看到,这里去加载了一个project.properties的配置文件。所以我们需要将aliyun-java-sdk-core SDK中的这个配置文件里的内容给拿过来。可以看到,这里只是指定了版本号。
在这里插入图片描述
所以我们直接在代码里写死即可

static {
    Properties sysProps = System.getProperties();
    String coreVersion = "4.6.0";
    /*
    Properties props = new Properties();
    try {
        props.load(UserAgentConfig.class.getClassLoader().getResourceAsStream("project.properties"));
        coreVersion = props.getProperty("sdk.project.version");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }*/
    DEFAULT_MESSAGE = String.format("AlibabaCloud (%s; %s) Java/%s %s/%s", sysProps.getProperty("os.name"), sysProps
            .getProperty("os.arch"), sysProps.getProperty("java.runtime.version"), "Core", coreVersion);
}

4.7 依旧报错 : 未找到endpoints.json

接着运行,发现报这个错

Process: com.heiko.alitingwu, PID: 8356
java.lang.ExceptionInInitializerError
	at com.aliyuncs.endpoint.DefaultEndpointResolver.<init>(DefaultEndpointResolver.java:33)
	at com.aliyuncs.endpoint.DefaultEndpointResolver.<init>(DefaultEndpointResolver.java:54)
	at com.aliyuncs.DefaultAcsClient.<init>(DefaultAcsClient.java:117)
	at com.aliyuncs.DefaultAcsClient.<init>(DefaultAcsClient.java:105)
	at com.heiko.alitingwu.TranscriptionTest.testFiletrans(TranscriptionTest.java:45)
	at com.heiko.alitingwu.MainActivity.onCreate$lambda$1(MainActivity.kt:25)
	at com.heiko.alitingwu.MainActivity.$r8$lambda$brY7-m4iUte_gFeK6bCl_RDuPSw(Unknown Source:0)
	at com.heiko.alitingwu.MainActivity$$ExternalSyntheticLambda1.onClick(D8$$SyntheticClass:0)
	at android.view.View.performClick(View.java:7741)
	at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1218)
	at android.view.View.performClickInternal(View.java:7711)
	at android.view.View.-$$Nest$mperformClickInternal(Unknown Source:0)
	at android.view.View$PerformClick.run(View.java:30620)
	at android.os.Handler.handleCallback(Handler.java:958)
	at android.os.Handler.dispatchMessage(Handler.java:99)
	at android.os.Looper.loopOnce(Looper.java:257)
	at android.os.Looper.loop(Looper.java:368)
	at android.app.ActivityThread.main(ActivityThread.java:8826)
	at java.lang.reflect.Method.invoke(Native Method)
	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:572)
	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1049)
Caused by: java.lang.NullPointerException: source
	at java.util.Objects.requireNonNull(Objects.java:232)
	at java.util.Scanner.<init>(Scanner.java:601)
	at java.util.Scanner.<init>(Scanner.java:587)
	at com.aliyuncs.endpoint.LocalConfigRegionalEndpointResolver.<clinit>(LocalConfigRegionalEndpointResolver.java:28)
	at com.aliyuncs.endpoint.DefaultEndpointResolver.<init>(DefaultEndpointResolver.java:33) 
	at com.aliyuncs.endpoint.DefaultEndpointResolver.<init>(DefaultEndpointResolver.java:54) 
	at com.aliyuncs.DefaultAcsClient.<init>(DefaultAcsClient.java:117) 
	at com.aliyuncs.DefaultAcsClient.<init>(DefaultAcsClient.java:105) 
	at com.heiko.alitingwu.TranscriptionTest.testFiletrans(TranscriptionTest.java:45) 
	at com.heiko.alitingwu.MainActivity.onCreate$lambda$1(MainActivity.kt:25) 
	at com.heiko.alitingwu.MainActivity.$r8$lambda$brY7-m4iUte_gFeK6bCl_RDuPSw(Unknown Source:0) 
	at com.heiko.alitingwu.MainActivity$$ExternalSyntheticLambda1.onClick(D8$$SyntheticClass:0) 
	at android.view.View.performClick(View.java:7741) 
	at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1218) 
	at android.view.View.performClickInternal(View.java:7711) 
	at android.view.View.-$$Nest$mperformClickInternal(Unknown Source:0) 
	at android.view.View$PerformClick.run(View.java:30620) 
	at android.os.Handler.handleCallback(Handler.java:958) 
	at android.os.Handler.dispatchMessage(Handler.java:99) 
	at android.os.Looper.loopOnce(Looper.java:257) 
	at android.os.Looper.loop(Looper.java:368) 
	at android.app.ActivityThread.main(ActivityThread.java:8826) 
	at java.lang.reflect.Method.invoke(Native Method) 
	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:572) 
	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1049) 

具体报错定位到LocalConfigRegionalEndpointResolver

protected static final String ENDPOINT_JSON = "endpoints.json";

static {
    Scanner scanner = null;
    try {
        ClassLoader classLoader = LocalConfigRegionalEndpointResolver.class.getClassLoader();
        InputStream is = classLoader.getResourceAsStream(ENDPOINT_JSON);
        scanner = new Scanner(is, "UTF-8");
        scanner.useDelimiter("\0");
        String jsonStr = scanner.hasNext() ? scanner.next() : "";
        ENDPOINTS_JSON = JsonParser.parseString(jsonStr).getAsJsonObject();
    } finally {
        if (null != scanner) {
            scanner.close();
        }
    }
}

可以看到,这里去读取了endpoints.json这个文件,同样我们去aliyun-java-sdk-core SDK里,找到endpoints.json在这里插入图片描述
这里发现endpoints.json这个文件里数据比较多,所以我们将这个文件直接复制到Android项目的asserts文件夹下
在这里插入图片描述
接着在代码中去读取这个文件

static {
    Scanner scanner = null;
    try {
        //ClassLoader classLoader = LocalConfigRegionalEndpointResolver.class.getClassLoader();
        //InputStream is = classLoader.getResourceAsStream(ENDPOINT_JSON);
        InputStream is = null;
        try {
            is = MyApp.getContext().getAssets().open(ENDPOINT_JSON);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        scanner = new Scanner(is, "UTF-8");
        scanner.useDelimiter("\0");
        String jsonStr = scanner.hasNext() ? scanner.next() : "";
        ENDPOINTS_JSON = JsonParser.parseString(jsonStr).getAsJsonObject();
    } finally {
        if (null != scanner) {
            scanner.close();
        }
    }
}

4.8 依旧报错 : 未找到DatatypeFactoryImpl

接着运行,会报这个错ClassNotFoundException: Didn't find class "org.apache.xerces.jaxp.datatype.DatatypeFactoryImpl",看字面意思,Class没找到,不得其解。

Process: com.heiko.alitingwu, PID: 13766
	java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
		at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:582)
		at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1049)
	Caused by: java.lang.reflect.InvocationTargetException
		at java.lang.reflect.Method.invoke(Native Method)
		at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:572)
		at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1049) 
	Caused by: com.aliyuncs.exceptions.ClientException: SDK.RequestTryOrRetryFailed : Some errors occurred. Error message for latest request is javax.xml.datatype.DatatypeConfigurationException: Provider org.apache.xerces.jaxp.datatype.DatatypeFactoryImpl not found
		at com.aliyuncs.DefaultAcsClient.doRealAction(DefaultAcsClient.java:458)
		at com.aliyuncs.DefaultAcsClient.doAction(DefaultAcsClient.java:318)
		at com.aliyuncs.DefaultAcsClient.doAction(DefaultAcsClient.java:243)
		at com.aliyuncs.DefaultAcsClient.doAction(DefaultAcsClient.java:124)
		at com.aliyuncs.DefaultAcsClient.getCommonResponse(DefaultAcsClient.java:197)
		at com.heiko.alitingwu.TranscriptionTest.testFiletrans(TranscriptionTest.java:46)
		at com.heiko.alitingwu.MainActivity.onCreate$lambda$1(MainActivity.kt:25)
		at com.heiko.alitingwu.MainActivity.$r8$lambda$brY7-m4iUte_gFeK6bCl_RDuPSw(Unknown Source:0)
		at com.heiko.alitingwu.MainActivity$$ExternalSyntheticLambda1.onClick(D8$$SyntheticClass:0)
		at android.view.View.performClick(View.java:7741)
		at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1218)
		at android.view.View.performClickInternal(View.java:7711)
		at android.view.View.-$$Nest$mperformClickInternal(Unknown Source:0)
		at android.view.View$PerformClick.run(View.java:30620)
		at android.os.Handler.handleCallback(Handler.java:958)
		at android.os.Handler.dispatchMessage(Handler.java:99)
		at android.os.Looper.loopOnce(Looper.java:257)
		at android.os.Looper.loop(Looper.java:368)
		at android.app.ActivityThread.main(ActivityThread.java:8826)
		at java.lang.reflect.Method.invoke(Native Method) 
		at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:572) 
		at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1049) 
	Caused by: java.lang.Error: javax.xml.datatype.DatatypeConfigurationException: Provider org.apache.xerces.jaxp.datatype.DatatypeFactoryImpl not found
		at javax.xml.bind.DatatypeConverterImpl.<clinit>(DatatypeConverterImpl.java:907)
		at javax.xml.bind.DatatypeConverter.initConverter(DatatypeConverter.java:155)
		at javax.xml.bind.DatatypeConverter.printBase64Binary(DatatypeConverter.java:626)
		at com.aliyuncs.auth.signers.HmacSHA1Signer.signString(HmacSHA1Signer.java:25)
		at com.aliyuncs.auth.signers.HmacSHA1Signer.signString(HmacSHA1Signer.java:37)
		at com.aliyuncs.RoaAcsRequest.signRequest(RoaAcsRequest.java:217)
		at com.aliyuncs.DefaultAcsClient.doRealAction(DefaultAcsClient.java:390)
		at com.aliyuncs.DefaultAcsClient.doAction(DefaultAcsClient.java:318) 
		at com.aliyuncs.DefaultAcsClient.doAction(DefaultAcsClient.java:243) 
		at com.aliyuncs.DefaultAcsClient.doAction(DefaultAcsClient.java:124) 
		at com.aliyuncs.DefaultAcsClient.getCommonResponse(DefaultAcsClient.java:197) 
		at com.heiko.alitingwu.TranscriptionTest.testFiletrans(TranscriptionTest.java:46) 
		at com.heiko.alitingwu.MainActivity.onCreate$lambda$1(MainActivity.kt:25) 
		at com.heiko.alitingwu.MainActivity.$r8$lambda$brY7-m4iUte_gFeK6bCl_RDuPSw(Unknown Source:0) 
		at com.heiko.alitingwu.MainActivity$$ExternalSyntheticLambda1.onClick(D8$$SyntheticClass:0) 
		at android.view.View.performClick(View.java:7741) 
		at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1218) 
		at android.view.View.performClickInternal(View.java:7711) 
		at android.view.View.-$$Nest$mperformClickInternal(Unknown Source:0) 
		at android.view.View$PerformClick.run(View.java:30620) 
		at android.os.Handler.handleCallback(Handler.java:958) 
		at android.os.Handler.dispatchMessage(Handler.java:99) 
		at android.os.Looper.loopOnce(Looper.java:257) 
		at android.os.Looper.loop(Looper.java:368) 
		at android.app.ActivityThread.main(ActivityThread.java:8826) 
		at java.lang.reflect.Method.invoke(Native Method) 
		at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:572) 
		at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1049) 
	Caused by: javax.xml.datatype.DatatypeConfigurationException: Provider org.apache.xerces.jaxp.datatype.DatatypeFactoryImpl not found
		at javax.xml.datatype.DatatypeFactory.newInstance(DatatypeFactory.java:106)
		at javax.xml.bind.DatatypeConverterImpl.<clinit>(DatatypeConverterImpl.java:905)
		at javax.xml.bind.DatatypeConverter.initConverter(DatatypeConverter.java:155) 
		at javax.xml.bind.DatatypeConverter.printBase64Binary(DatatypeConverter.java:626) 
		at com.aliyuncs.auth.signers.HmacSHA1Signer.signString(HmacSHA1Signer.java:25) 
		at com.aliyuncs.auth.signers.HmacSHA1Signer.signString(HmacSHA1Signer.java:37) 
		at com.aliyuncs.RoaAcsRequest.signRequest(RoaAcsRequest.java:217) 
		at com.aliyuncs.DefaultAcsClient.doRealAction(DefaultAcsClient.java:390) 
		at com.aliyuncs.DefaultAcsClient.doAction(DefaultAcsClient.java:318) 
		at com.aliyuncs.DefaultAcsClient.doAction(DefaultAcsClient.java:243) 
		at com.aliyuncs.DefaultAcsClient.doAction(DefaultAcsClient.java:124) 
		at com.aliyuncs.DefaultAcsClient.getCommonResponse(DefaultAcsClient.java:197) 
		at com.heiko.alitingwu.TranscriptionTest.testFiletrans(TranscriptionTest.java:46) 
		at com.heiko.alitingwu.MainActivity.onCreate$lambda$1(MainActivity.kt:25) 
		at com.heiko.alitingwu.MainActivity.$r8$lambda$brY7-m4iUte_gFeK6bCl_RDuPSw(Unknown Source:0) 
		at com.heiko.alitingwu.MainActivity$$ExternalSyntheticLambda1.onClick(D8$$SyntheticClass:0) 
		at android.view.View.performClick(View.java:7741) 
		at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1218) 
		at android.view.View.performClickInternal(View.java:7711) 
		at android.view.View.-$$Nest$mperformClickInternal(Unknown Source:0) 
		at android.view.View$PerformClick.run(View.java:30620) 
		at android.os.Handler.handleCallback(Handler.java:958) 
		at android.os.Handler.dispatchMessage(Handler.java:99) 
		at android.os.Looper.loopOnce(Looper.java:257) 
		at android.os.Looper.loop(Looper.java:368) 
		at android.app.ActivityThread.main(ActivityThread.java:8826) 
		at java.lang.reflect.Method.invoke(Native Method) 
		at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:572) 
		at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1049) 
	Caused by: java.lang.ClassNotFoundException: Didn't find class "org.apache.xerces.jaxp.datatype.DatatypeFactoryImpl" on path: DexPathList[[zip file "/data/app/~~XycsvDMeKh2xNAenY3TNTg==/com.heiko.alitingwu-Rw0fT2I35O8n_v2zLu3jww==/base.apk"],nativeLibraryDirectories=[/data/app/~~XycsvDMeKh2xNAenY3TNTg==/com.heiko.alitingwu-Rw0fT2I35O8n_v2zLu3jww==/lib/arm64, /system/lib64, /system_ext/lib64]]
		at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:259)
		at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
		at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
		at javax.xml.datatype.FactoryFinder.newInstance(FactoryFinder.java:157)
		at javax.xml.datatype.FactoryFinder.find(FactoryFinder.java:223)
		at javax.xml.datatype.DatatypeFactory.newInstance(DatatypeFactory.java:99)
		at javax.xml.bind.DatatypeConverterImpl.<clinit>(DatatypeConverterImpl.java:905) 
		at javax.xml.bind.DatatypeConverter.initConverter(DatatypeConverter.java:155) 
		at javax.xml.bind.DatatypeConverter.printBase64Binary(DatatypeConverter.java:626) 
		at com.aliyuncs.auth.signers.HmacSHA1Signer.signString(HmacSHA1Signer.java:25) 
		at com.aliyuncs.auth.signers.HmacSHA1Signer.signString(HmacSHA1Signer.java:37) 
		at com.aliyuncs.RoaAcsRequest.signRequest(RoaAcsRequest.java:217) 
		at com.aliyuncs.DefaultAcsClient.doRealAction(DefaultAcsClient.java:390) 
		at com.aliyuncs.DefaultAcsClient.doAction(DefaultAcsClient.java:318) 
		at com.aliyuncs.DefaultAcsClient.doAction(DefaultAcsClient.java:243) 
		at com.aliyuncs.DefaultAcsClient.doAction(DefaultAcsClient.java:124) 
		at com.aliyuncs.DefaultAcsClient.getCommonResponse(DefaultAcsClient.java:197) 
		at com.heiko.alitingwu.TranscriptionTest.testFiletrans(TranscriptionTest.java:46) 
		at com.heiko.alitingwu.MainActivity.onCreate$lambda$1(MainActivity.kt:25) 
		at com.heiko.alitingwu.MainActivity.$r8$lambda$brY7-m4iUte_gFeK6bCl_RDuPSw(Unknown Source:0) 
		at com.heiko.alitingwu.MainActivity$$ExternalSyntheticLambda1.onClick(D8$$SyntheticClass:0) 
		at android.view.View.performClick(View.java:7741) 
		at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1218) 
		at android.view.View.performClickInternal(View.java:7711) 
		at android.view.View.-$$Nest$mperformClickInternal(Unknown Source:0) 
		at android.view.View$PerformClick.run(View.java:30620) 
		at android.os.Handler.handleCallback(Handler.java:958) 
		at android.os.Handler.dispatchMessage(Handler.java:99) 
		at android.os.Looper.loopOnce(Looper.java:257) 
		at android.os.Looper.loop(Looper.java:368) 
		at android.app.ActivityThread.main(ActivityThread.java:8826) 
		at java.lang.reflect.Method.invoke(Native Method) 
		at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:572) 
		at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1049) 

最终是定位到HmacSHA1Signer类里的这行代码DatatypeConverter.printBase64Binary(signData);

@Override
public String signString(String stringToSign, String accessKeySecret) {
    try {
        Mac mac = Mac.getInstance(ALGORITHM_NAME);
        mac.init(new SecretKeySpec(accessKeySecret.getBytes(ENCODING), ALGORITHM_NAME));
        byte[] signData = mac.doFinal(stringToSign.getBytes(ENCODING));
        return DatatypeConverter.printBase64Binary(signData);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException(e.toString());
    } catch (UnsupportedEncodingException e) {
        throw new IllegalArgumentException(e.toString());
    } catch (InvalidKeyException e) {
        throw new IllegalArgumentException(e.toString());
    }
}

看上去解决这个ClassNotFoundException没找到的问题比较难,所以我这里想绕过这个问题。
我们进入printBase64Binary方法看下源码,可以发现最终只调用了这些代码,所以我们把这些代码复制出来

public static String _printBase64Binary(byte[] input) {
    return _printBase64Binary(input, 0, input.length);
}

public static String _printBase64Binary(byte[] input, int offset, int len) {
    char[] buf = new char[((len + 2) / 3) * 4];
    int ptr = _printBase64Binary(input, offset, len, buf, 0);
    assert ptr == buf.length;
    return new String(buf);
}

private static final char[] encodeMap = initEncodeMap();

private static char[] initEncodeMap() {
    char[] map = new char[64];
    int i;
    for (i = 0; i < 26; i++) {
        map[i] = (char) ('A' + i);
    }
    for (i = 26; i < 52; i++) {
        map[i] = (char) ('a' + (i - 26));
    }
    for (i = 52; i < 62; i++) {
        map[i] = (char) ('0' + (i - 52));
    }
    map[62] = '+';
    map[63] = '/';

    return map;
}

public static char encode(int i) {
    return encodeMap[i & 0x3F];
}

public static int _printBase64Binary(byte[] input, int offset, int len, char[] buf, int ptr) {
    // encode elements until only 1 or 2 elements are left to encode
    int remaining = len;
    int i;
    for (i = offset;remaining >= 3; remaining -= 3, i += 3) {
        buf[ptr++] = encode(input[i] >> 2);
        buf[ptr++] = encode(
                ((input[i] & 0x3) << 4)
                        | ((input[i + 1] >> 4) & 0xF));
        buf[ptr++] = encode(
                ((input[i + 1] & 0xF) << 2)
                        | ((input[i + 2] >> 6) & 0x3));
        buf[ptr++] = encode(input[i + 2] & 0x3F);
    }
    // encode when exactly 1 element (left) to encode
    if (remaining == 1) {
        buf[ptr++] = encode(input[i] >> 2);
        buf[ptr++] = encode(((input[i]) & 0x3) << 4);
        buf[ptr++] = '=';
        buf[ptr++] = '=';
    }
    // encode when exactly 2 elements (left) to encode
    if (remaining == 2) {
        buf[ptr++] = encode(input[i] >> 2);
        buf[ptr++] = encode(((input[i] & 0x3) << 4)
                | ((input[i + 1] >> 4) & 0xF));
        buf[ptr++] = encode((input[i + 1] & 0xF) << 2);
        buf[ptr++] = '=';
    }
    return ptr;
}

DatatypeConverter.printBase64Binary(signData);的调用改为调用return _printBase64Binary(signData);

4.9 依旧报错 : 乍一看报错日志很多

接着运行,发现这个报错,乍一看报错很多

Process: com.heiko.alitingwu, PID: 15249
	java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
		at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:582)
		at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1049)
	Caused by: java.lang.reflect.InvocationTargetException
		at java.lang.reflect.Method.invoke(Native Method)
		at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:572)
		at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1049) 
	Caused by: com.aliyuncs.exceptions.ClientException: SDK.RequestTryOrRetryFailed : Some errors occurred. Error message for latest request is null
		at com.aliyuncs.DefaultAcsClient.doRealAction(DefaultAcsClient.java:458)
		at com.aliyuncs.DefaultAcsClient.doAction(DefaultAcsClient.java:318)
		at com.aliyuncs.DefaultAcsClient.doAction(DefaultAcsClient.java:243)
		at com.aliyuncs.DefaultAcsClient.doAction(DefaultAcsClient.java:124)
		at com.aliyuncs.DefaultAcsClient.getCommonResponse(DefaultAcsClient.java:197)
		at com.heiko.alitingwu.TranscriptionTest.testFiletrans(TranscriptionTest.java:46)
		at com.heiko.alitingwu.MainActivity.onCreate$lambda$1(MainActivity.kt:25)
		at com.heiko.alitingwu.MainActivity.$r8$lambda$brY7-m4iUte_gFeK6bCl_RDuPSw(Unknown Source:0)
		at com.heiko.alitingwu.MainActivity$$ExternalSyntheticLambda1.onClick(D8$$SyntheticClass:0)
		at android.view.View.performClick(View.java:7741)
		at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1218)
		at android.view.View.performClickInternal(View.java:7711)
		at android.view.View.-$$Nest$mperformClickInternal(Unknown Source:0)
		at android.view.View$PerformClick.run(View.java:30620)
		at android.os.Handler.handleCallback(Handler.java:958)
		at android.os.Handler.dispatchMessage(Handler.java:99)
		at android.os.Looper.loopOnce(Looper.java:257)
		at android.os.Looper.loop(Looper.java:368)
		at android.app.ActivityThread.main(ActivityThread.java:8826)
		at java.lang.reflect.Method.invoke(Native Method) 
		at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:572) 
		at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1049) 
	Caused by: android.os.NetworkOnMainThreadException
		at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1739)
		at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:115)
		at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:103)
		at java.net.InetAddress.getAllByName(InetAddress.java:1152)
		at cz.msebera.android.httpclient.impl.conn.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:45)
		at cz.msebera.android.httpclient.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:113)
		at cz.msebera.android.httpclient.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:374)
		at cz.msebera.android.httpclient.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:393)
		at cz.msebera.android.httpclient.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
		at cz.msebera.android.httpclient.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)
		at cz.msebera.android.httpclient.impl.execchain.RetryExec.execute(RetryExec.java:89)
		at cz.msebera.android.httpclient.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
		at cz.msebera.android.httpclient.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
		at cz.msebera.android.httpclient.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
		at cz.msebera.android.httpclient.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108)
		at com.aliyuncs.http.clients.ApacheHttpClient.syncInvoke(ApacheHttpClient.java:350)
		at com.aliyuncs.DefaultAcsClient.doRealAction(DefaultAcsClient.java:396)
		at com.aliyuncs.DefaultAcsClient.doAction(DefaultAcsClient.java:318) 
		at com.aliyuncs.DefaultAcsClient.doAction(DefaultAcsClient.java:243) 
		at com.aliyuncs.DefaultAcsClient.doAction(DefaultAcsClient.java:124) 
		at com.aliyuncs.DefaultAcsClient.getCommonResponse(DefaultAcsClient.java:197) 
		at com.heiko.alitingwu.TranscriptionTest.testFiletrans(TranscriptionTest.java:46) 
		at com.heiko.alitingwu.MainActivity.onCreate$lambda$1(MainActivity.kt:25) 
		at com.heiko.alitingwu.MainActivity.$r8$lambda$brY7-m4iUte_gFeK6bCl_RDuPSw(Unknown Source:0) 
		at com.heiko.alitingwu.MainActivity$$ExternalSyntheticLambda1.onClick(D8$$SyntheticClass:0) 
		at android.view.View.performClick(View.java:7741) 
		at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1218) 
		at android.view.View.performClickInternal(View.java:7711) 
		at android.view.View.-$$Nest$mperformClickInternal(Unknown Source:0) 
		at android.view.View$PerformClick.run(View.java:30620) 
		at android.os.Handler.handleCallback(Handler.java:958) 
		at android.os.Handler.dispatchMessage(Handler.java:99) 
		at android.os.Looper.loopOnce(Looper.java:257) 
		at android.os.Looper.loop(Looper.java:368) 
		at android.app.ActivityThread.main(ActivityThread.java:8826) 
		at java.lang.reflect.Method.invoke(Native Method) 
		at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:572) 
		at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1049) 

定眼一看发现有这么一句Caused by: android.os.NetworkOnMainThreadException
哦,这个调用要在异步线程,所以我们让其跑在异步线程。

binding.btnTest1.setOnClickListener {
    Thread {
        TranscriptionTest().testFiletrans()
    }.start()
}

5. 再次运行

可以发现运行成功了,打印出了如下日志

{"Code":"0","Data":{"TaskId":"5de301246fac411b8cc2bec2b2388d6b","TaskKey":"task1712908506219","TaskStatus":"ONGOING"},"Message":"success","RequestId":"9F757993-29AD-56F4-99FA-A0A55255930F"}

到这里,阿里听悟接入Android的兼容性问题就都已经解决了。接着我们可以再来调用下阿里听悟SDK的其他方法。

5.1 获取任务状态

这个是用来查询任务的状态

public class GetTaskInfoTest {

    public void getTaskInfo(String taskId) throws ClientException {
        //String taskId = "请输入创建任务(含离线转写、实时会议)的TaskId";
        String queryUrl = String.format("/openapi/tingwu/v2/tasks" + "/%s", taskId);

        CommonRequest request = createCommonRequest("tingwu.cn-beijing.aliyuncs.com", "2023-09-30", ProtocolType.HTTPS, MethodType.GET, queryUrl);
        DefaultProfile profile = DefaultProfile.getProfile("cn-beijing", Constants.AccessKeyId,Constants.AccessKeyPassword);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonResponse response = client.getCommonResponse(request);
        System.out.println(response.getData());
    }
    public static CommonRequest createCommonRequest(String domain, String version, ProtocolType protocolType, MethodType method, String uri) {
        // 创建API请求并设置参数
        CommonRequest request = new CommonRequest();
        request.setSysDomain(domain);
        request.setSysVersion(version);
        request.setSysProtocol(protocolType);
        request.setSysMethod(method);
        request.setSysUriPattern(uri);
        request.setHttpContentType(FormatType.JSON);
        return request;
    }
}

进行调用

binding.btnTest2.setOnClickListener {
    Thread {
        GetTaskInfoTest().getTaskInfo("5de301246fac411b8cc2bec2b2388d6b")
    }.start()
}

可以发现打印如下日志

{"Code":"0","Data":{"TaskId":"5de301246fac411b8cc2bec2b2388d6b","TaskKey":"task1712908506219","TaskStatus":"COMPLETED","Result":{"Transcription":"https://prod-tingwu-paas-common-beijing.oss-cn-beijing.aliyuncs.com/tingwu/output/1171512458371407/5de301246fac411b8cc2bec2b2388d6b/5de301246fac411b8cc2bec2b2388d6b_Transcription_20240412155610.json?Expires=1715500695&OSSAccessKeyId=LTAI5tMzZ1D4o1drkJN1TfCr&Signature=p8ecCBYeWvPaMzkwN13rz1EL9Ps%3D"}},"Message":"success","RequestId":"53E7CFC5-4B3F-5B36-8EB0-64DCB78F684D"}

表明这个音视频文件离线转写任务已经完成了,具体转写后的文本在Transcription这个字段的URL中。

{
    "TaskId": "5de301246fac411b8cc2bec2b2388d6b",
    "Transcription": {
        "AudioInfo": {
            "Size": 13710403,
            "Duration": 1713790,
            "SampleRate": 44100
        },
        "Paragraphs": [
            {
                "ParagraphId": "1712904561163500000",
                "SpeakerId": "1",
                "Words": [
                    {
                        "Id": 10,
                        "SentenceId": 1,
                        "Start": 1100,
                        "End": 1960,
                        "Text": "Hello, "
                    },
                    {
                        "Id": 20,
                        "SentenceId": 1,
                        "Start": 2760,
                        "End": 3100,
                        "Text": "this "
                    },
                    {
                        "Id": 30,
                        "SentenceId": 1,
                        "Start": 3100,
                        "End": 3290,
                        "Text": "is "
                    },
                    {
                        "Id": 40,
                        "SentenceId": 1,
                        "Start": 3300,
                        "End": 3500,
                        "Text": "the "
                    },
                    {
                        "Id": 50,
                        "SentenceId": 1,
                        "Start": 3500,
                        "End": 4420,
                        "Text": "University of "
                    },
                    {
                        "Id": 60,
                        "SentenceId": 1,
                        "Start": 4430,
                        "End": 5110,
                        "Text": "Cambridge "
                    },
                    {
                        "Id": 70,
                        "SentenceId": 1,
                        "Start": 5110,
                        "End": 5860,
                        "Text": "Mover's "
                    },
                    {
                        "Id": 80,
                        "SentenceId": 1,
                        "Start": 5860,
                        "End": 6410,
                        "Text": "listening "
                    },
                    
	//内容过多,这里就省略了.......

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1701081.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

舞蹈工作室会员服务预约门店管理系统小程序的作用是什么

舞蹈涵盖少儿、街舞、芭蕾、拉丁等多个细分类目&#xff0c;舞蹈工作室除了商演外&#xff0c;内部还有学员培训教育等&#xff0c;提高营收和提升服务效率是商家一直需要思考的问题&#xff0c;线上化程度加深&#xff0c;需要满足客户个性化需求且快速完成流程。 运用【雨科…

windows11下,使用工具验证下载的iso文件完整性

windows11下&#xff0c;要验证下载的iso文件是否正常&#xff0c;可以使用工具生成md5值&#xff0c;再与下载源提供的md5值进行比较&#xff0c;相同&#xff0c;说明下载的正常。 命令如下&#xff1a; certutil -hashfile iso文件名 md5 如下面的例子&#xff0c;生成d…

VGG论文解析—Very Deep Convolutional Networks for Large-Scale Image Recognition

VGG论文解析—Very Deep Convolutional Networks for Large-Scale Image Recognition -2015 研究背景 大规模图像识别的深度卷积神经网络 VGG&#xff08;牛津大学视觉几何组&#xff09; 认识数据集&#xff1a;ImageNet的大规模图像识别挑战赛 LSVRC-2014&#xff1a;Image…

【EI会议】2024年互联网技术与环境工程国际会议(IACITEE 2024)

【EI会议】2024年互联网技术与环境工程国际会议&#xff08;IACITEE 2024&#xff09; 2024 International Conference on Internet Technology and Environmental Engineering 互联网技术与环境工程国际会议&#xff08;IACITEE 2024&#xff09;将在重庆举行&#xff0c;主…

R包显示颜色条

方式1 rm(listls()) ncolors 5 data data.frame(valuerep(5,ncolors)) # 一定要加入这个结果的 colors colorRampPalette(c("blue","red"))(nrow(data)) #colors c(#0000FF,#3F00BF,#7F007F,#BF003F,#FF0000) barplot(data$value,colcolors,names.arg …

高光谱成像技术简介,怎么选择成像方案?

目录 一、什么是光谱&#xff1f;二、光谱和光谱分析方法的类型三、多光谱和高光谱的区别四、高光谱在水果品质检测中的应用1. 高光谱成像系统2. 高光谱图像的获取方式3. 高光谱图像处理与分析4. 在水果品质检测中的应用总结 五、针对自己的应用场景怎么使用高光谱技术六、参考…

【量算分析工具-水平距离】GeoServer改造Springboot番外系列四

水平距离 水平距离计算方式&#xff0c;我目前接触到的有四种&#xff1a;Flat Earth距离、大圆路径距离&#xff08;Haversine公式&#xff09;、JTS库方法&#xff08;黑盒&#xff09;、测地距离&#xff08;Vincenty公式&#xff09;。 说明&#xff1a;这里的EARTH_RADIUS…

30多万汉字词语押韵查询ACCESS\EXCEL数据库

押韵&#xff0c;也作“压韵”。作诗词曲赋等韵文时在句末或联末用同韵的字相押&#xff0c;称为押韵。诗歌押韵&#xff0c;使作品声韵和谐&#xff0c;便于吟诵和记忆&#xff0c;具有节奏和声调美。旧时押韵&#xff0c;要求韵部相同或相通&#xff0c;也有少数变格。现代新…

Hadoop3:HDFS中NameNode和SecondaryNameNode的工作机制(较复杂)

一、HDFS存储数据的机制简介 HDFS存储元数据(meta data)的时候 结果&#xff0c;记录在fsImage文件里 过程&#xff0c;记录在Edits文件里 同时fsImageEdits最终结果&#xff0c;这个最终结果&#xff08;fsImageEdits&#xff09;会保存一份在内存中&#xff0c;为了提升性能…

JVM 常见配置参数

JVM 配置常见参数 Java虚拟机的参数&#xff0c;在启动jar包的时候通过java 命令指定JVM参数 -options表示Java虚拟机的启动参数&#xff0c;class为带有main()函数的Java类&#xff0c;args表示传递给主函数main()的参数。 一、系统查看参数: -XX:PrintVMOptions可以在程序…

ES的安装以及配置+ik分词

环境&#xff1a;windows10、ES&#xff08;8.13.3&#xff09;、Kibana&#xff08;8.13.3&#xff09;、Logstash&#xff08;8.13.3&#xff09;、ik&#xff08;8.13.3&#xff09; 1.下载安装ES Download Elasticsearch | ElasticDownload Elasticsearch or the complet…

四元数学习总结(2)

导语&#xff1a;相比矩阵&#xff0c;用四元数处理3D旋转的优势是毋庸置疑的&#xff0c;但由于概念复杂&#xff0c;难于理解&#xff0c;一直令我摸不着头脑。最近学习更是发现在机器人、无人机、SLAM等先进领域&#xff0c;四元数被当成实数、整数这样的基础&#xff0c;所…

超简单白话文机器学习 - 支持向量机SVM(含算法讲解,公式全解,手写代码实现,调包实现)

1. 支持向量机SVM 支持向量机&#xff0c;因其英文名为support vector machine&#xff0c;故一般简称SVM&#xff0c;通俗来讲&#xff0c;它是一种二类分类模型&#xff0c;其基本模型定义为特征空间上的间隔最大的线性分类器&#xff0c;其学习策略便是间隔最大化&#xff…

学浪的缓存怎么导出来

学浪的缓存导出问题困扰着许多用户&#xff0c;备份和管理数据变得至关重要。在数字化时代&#xff0c;保护和利用数据是企业和个人不可或缺的需求。在这篇文章中&#xff0c;我们将深入探讨学浪缓存导出的方法&#xff0c;为您解决疑惑&#xff0c;让您轻松掌握数据的安全与便…

java:程序包javax. servLet不存在

一.原因 1.项目Tomcat 服务器依赖未导入 2.项目的 SDK 版本选择错误 二.解决方法 方案一&#xff1a; 1.选择项目结构选项 2.导入Tomcat依赖 把tomcat里面的【jsp-api.jar】和【servlet-api.jar】这两个包导入 方案二&#xff1a; 1.选择项目结构选项 2.选择自己的jdk版本…

海外短剧系统源码

随着互联网的普及和全球化的加速&#xff0c;海外短剧系统源码的开发成为了一个新兴的领域。海外短剧&#xff0c;即那些在海外市场流行的短视频剧集&#xff0c;以其短小精悍、节奏快速、内容多样的特点&#xff0c;迅速吸引了全球观众的注意。本文将探讨海外短剧系统源码的开…

反对加征关税,特斯拉上海厂传减产20% | 百能云芯

特斯拉公司首席执行官马斯克近日在公开场合表达了对美国计划对中国电动车加征关税的反对立场&#xff0c;强调特斯拉不支持任何扭曲市场的举措。据知情人士透露&#xff0c;特斯拉上海工厂正计划在今年第二季度至少削减Model Y车型的产量20%&#xff0c;以应对市场需求的变化。…

需求跟踪矩阵是什么?怎么创建?一文详解

一、什么是需求跟踪矩阵 对项目经理或产品经理来说&#xff0c;需求清单肯定不陌生&#xff0c;那什么是需求跟踪矩阵呢&#xff1f; 需求跟踪矩阵&#xff08;Requirement Track Matrix&#xff0c;简称RTM &#xff09;&#xff0c;是把产品需求从其来源连接到能满足需求的…

大模型应用之基于Langchain的测试用例生成

一 用例生成实践效果 在组内的日常工作安排中&#xff0c;持续优化测试技术、提高测试效率始终是重点任务。近期&#xff0c;我们在探索实践使用大模型生成测试用例&#xff0c;期望能够借助其强大的自然语言处理能力&#xff0c;自动化地生成更全面和高质量的测试用例。 当前…

MIC工作原理(驻极体麦克风)

1.驻极体麦克风声电转换原理 如图所示&#xff0c;驻极体麦克风属于电容式麦克风&#xff0c;背极板和振膜构成平板版电容器&#xff0c;背极板驻有一定量的电荷&#xff0c;背极板通过金属环连接到FET的栅极&#xff1b;振膜镀层金属&#xff0c;通过金属外壳连接到FET的S极&…