我按照重新预订(http://www.redbooks.ibm.com/redbooks/pdfs/sg248393.pdf)中的步骤启动了一个小型Java应用程序。
我还创建了他们描述的API密钥。
现在,我收到了未经授权的访问:由于凭据消息无效,访问被拒绝。
package vrproject;
//Here you import Watson Java SDK to make it available in your code.
import com.ibm.watson.developer_cloud.visual_recognition.v3.*;
import com.ibm.watson.developer_cloud.visual_recognition.v3.model.*;
public class ClassifyImage {
public static void main(String[] args) {
// TODO Auto-generated method stub
VisualRecognition service = new VisualRecognition(VisualRecognition.VERSION_DATE_2016_05_20);
service.setEndPoint("https://gateway.watsonplatform.net/visual-recognition/api");
//Here you replace "your_api_key_here" by the API Key you created in "Creating
//a Watson Visual Recognition service instance and getting the API key"
service.setApiKey("123apikey");
//Here you add the URL of your image. The image size should not exceed 2MB.
String imageURL = new
String("https://raw.githubusercontent.com/watson-developer-cloud/doc-tutorial-downloads/master/visual-recog nition/fruitbowl.jpg");
ClassifyImagesOptions options = new ClassifyImagesOptions.Builder().url(imageURL).build();
VisualClassification result = service.classify(options).execute(); System.out.println("Classification Results:");
System.out.println(result);
}
}
错误信息:
Mär 05, 2020 7:02:23 PM com.ibm.watson.developer_cloud.service.WatsonService processServiceCall
SCHWERWIEGEND: POST https://gateway.watsonplatform.net/visual-recognition/api/v3/classify?version=2016-05-20&api_key=123apikey, status: 401, error: Unauthorized
Exception in thread "main" com.ibm.watson.developer_cloud.service.exception.UnauthorizedException: Unauthorized: Access is denied due to invalid credentials
at com.ibm.watson.developer_cloud.service.WatsonService.processServiceCall(WatsonService.java:418)
at com.ibm.watson.developer_cloud.service.WatsonService$1.execute(WatsonService.java:180)
at vrproject.ClassifyImage.main(ClassifyImage.java:22)
您知道我为什么会收到这些错误吗?
我不确定版本是否太旧,我只是使用本书中的版本。
最佳答案
该红皮书于2017年发布,它显示的身份验证机制已过时,并且已弃用其使用的SDK。您需要根据当前的API文档修改代码:https://cloud.ibm.com/apidocs/visual-recognition/visual-recognition-v3?code=java#classify-images
在编写示例代码时,
IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
VisualRecognition visualRecognition = new VisualRecognition("2018-03-19", authenticator);
visualRecognition.setServiceUrl("{url}");
InputStream imagesStream = new FileInputStream("./fruitbowl.jpg");
ClassifyOptions classifyOptions = new ClassifyOptions.Builder()
.imagesFile(imagesStream)
.classifierIds(Arrays.asList("food"))
.build();
ClassifiedImages result = visualRecognition.classify(classifyOptions).execute().getResult();
System.out.println(result);x
您的SDK依赖关系所在的位置
<dependency>
<groupId>com.ibm.watson</groupId>
<artifactId>ibm-watson</artifactId>
<version>8.3.0</version>
</dependency>