如何使用 IAM 授权授权 IBM Cloud Watson 服务

How authorize IBM Cloud Watson service using IAM authorization

我正在尝试通过 IBM 云 Java SDK 授权我的 IBM Cloud 语音转文本服务(IAM 授权)。尽管我的 API 密钥和服务 url 是正确的,但我仍然从服务器获得 401 not authorized

这是我的代码:

IamOptions iamOptions = new IamOptions.Builder().apiKey("dummy-api-key").url("dummy-url").build();
SpeechToText speechToText = new SpeechToText(iamOptions);

这是服务器响应(日志)

Aug. 09, 2018 10:44:01 PM okhttp3.internal.platform.Platform log
INFO: --> POST https://iam.bluemix.net/identity/token h2 (135-byte body)
Aug. 09, 2018 10:44:02 PM okhttp3.internal.platform.Platform log
INFO: <-- 200  https://iam.bluemix.net/identity/token (181ms, 1759-byte body)
Aug. 09, 2018 10:44:03 PM com.ibm.watson.developer_cloud.speech_to_text.v1.websocket.BaseRecognizeCallback onError
SEVERE: Expected HTTP 101 response but was '401 Not Authorized'
java.net.ProtocolException: Expected HTTP 101 response but was '401 Not Authorized'
    at okhttp3.internal.ws.RealWebSocket.checkResponse(RealWebSocket.java:216)
    at okhttp3.internal.ws.RealWebSocket.onResponse(RealWebSocket.java:183)
    at okhttp3.RealCall$AsyncCall.execute(RealCall.java:141)
    at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1135)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
    at java.base/java.lang.Thread.run(Thread.java:844)

我没有包含我的语音合成代码,因为它无关紧要。我检查了 IBM Java 文档和 IAM 文档。这就是他们在 IBM Cloud 中指示授权的方式。

IBM GitHub 页面 example

我成功了。您不传递 url 参数,而是将其设置为终点。

IamOptions iamOptions = new IamOptions.Builder().apiKey("ElPOiM4sMnO4CzJq7LEx1h-4dgaQcCNS1WgGYsnNi59D").build();
SpeechToText speechToText = new SpeechToText(iamOptions);
speechToText.setEndPoint("https://gateway-syd.watsonplatform.net/speech-to-text/api");