Java语言API示例
本示例以图像标签为例介绍如何使用JAVA调用API。
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;
/**
 * 此demo仅供测试使用,强烈建议使用SDK
 * 使用前需配置依赖jar包。jar包可通过下载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}/v2/{project_id}/image/tagging";
		String token = "用户获取得到的实际token值";
		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();
		}
	}
}
 | 
       参数  | 
     
       参数说明  | 
    
|---|---|
| 
       url  | 
     
       API请求URL,例如本示例中https://{endpoint}/v2/{project_id}/image/tagging。  | 
    
| 
       token  | 
     
       Token是用户的访问令牌,承载了用户的身份、权限等信息,用户调用API接口时,需要使用Token进行鉴权。 获取Token方法请参见认证鉴权。  | 
    
| 
       imgPath  | 
     
       图片路径。支持图片文件路径或图片url路径。其中,图片的url路径支持公网http/https url或OBS提供的url。  |