Java API Example
This section uses Image Tagging as an example to describe how to call Java APIs.
package com.huawei.ais.demo; import com.huawei.ais.sdk.util.HttpClientUtils; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.entity.StringEntity; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import com.alibaba.fastjson.JSONObject; import org.apache.http.entity.ContentType; import org.apache.http.message.BasicHeader; /** * This demo is used only for tests. You are advised to use the SDK. * Before using this demo, configure the dependent JAR package. Obtain this package by downloading the SDK. */ public class ImageTaggingDemo { public static void main(String[] args) throws URISyntaxException, UnsupportedOperationException, IOException{ TokenDemo(); } public static void TokenDemo() throws URISyntaxException, UnsupportedOperationException, IOException { String url = "https://{endpoint}/v1.0/image/tagging"; String token = "Actual token value obtained by the user"; String imgPath = "data/image-tagging.jpg"; //File path or URL of the image to be recognized. JSONObject params = new JSONObject(); try { if (imgPath.indexOf("http://") != -1 || imgPath.indexOf("https://") != -1) { params.put("url", imgPath); } else { byte[] fileData = FileUtils.readFileToByteArray(new File(imgPath)); String fileBase64Str = Base64.encodeBase64String(fileData); params.put("image", fileBase64Str); } Header[] headers = new Header[]{new BasicHeader("X-Auth-Token", token), new BasicHeader("Content-Type", ContentType.APPLICATION_JSON.toString())}; StringEntity stringEntity = new StringEntity(params.toJSONString(), "utf-8"); HttpResponse response = HttpClientUtils.post(url, headers, stringEntity); String content = IOUtils.toString(response.getEntity().getContent(), "utf-8"); System.out.println(content); } catch (Exception e) { e.printStackTrace(); } } }
Parameter |
Description |
---|---|
url |
API request URL, for example, https://{endpoint}/v1.0/image/tagging. |
token |
A token is a user's access credential, which includes user identities and permissions. When you call an API to access a cloud service, a token is required for identity authentication. For details about how to obtain the token, see . |
imgPath |
Image path. An image file path or image URL is supported. The URL can be an HTTP/HTTPS or OBS URL. |
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot