imagga api调用有多种方式,demo中用的是java调用,其调用方式必须先调用"https://api.imagga.com/v1/content"请求获得一个content Id ,然后将该Id作为参数再调用"https://api.imagga.com/v1/tagging?content="才能的到返回的tag 数据,具体调用方式如下:
################################# 该方法为执行方法 ###########################################
public static volatile String apiContent = "https://api.imagga.com/v1/content";
public static volatile String apiTagging = "https://api.imagga.com/v1/tagging?content=";
public static ImaggaTagsResultModel getTagsFromImaggaServerWithHttpClient(String authorization,File binaryFile) throws Exception {
//调用获取上传图片的 content Id的restful,返回HttpResponse
HttpResponse response = uploadFileWithHttpClient(apiContent, authorization, binaryFile);Map<String, Object> json = getHttpResponseJsonMap(response);
Map<String, Object> idMap = (Map<String, Object>) ((List) json.get("uploaded")).get(0);
String contentId = idMap.get("id").toString();
log.info("ContentId: "+contentId);
if (contentId != null) {Thread.sleep(1000);//7243f057f824e1ad290c72aae740b2c6
String taggingUrl = apiTagging + contentId;
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(taggingUrl);
request.setHeader(HttpHeaders.AUTHORIZATION, authorization);
HttpResponse taggingResponse = client.execute(request);
String taggingJson = HttpUtils.getHttpClientResult(taggingResponse);
log.info("TaggingJson: "+taggingJson);
Gson gson = new Gson();
ImaggaTagsResultModel result = gson.fromJson(taggingJson, ImaggaTagsResultModel.class);
return result;
}
Thread.sleep(1000);//7243f057f824e1ad290c72aae740b2c6
return null;
}
################################# 获取上传图片的 content Id 的Restful###########################################
public static HttpResponse uploadFileWithHttpClient(String url, String authorization, File targetFile ) throws IOException{
HttpClient client = HttpClientBuilder.create().build();
HttpPost httppost = new HttpPost(url);
httppost.setHeader("authorization", authorization);
FileBody fileBody = new FileBody(targetFile);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addPart(targetFile.getName(), fileBody);
HttpEntity entity = builder.build();
httppost.setEntity(entity);
HttpResponse response = client.execute(httppost);
return response;
}
################################# 将HttpResponse转为Map对象###########################################
public static Map<String, Object> getHttpResponseJsonMap(HttpResponse response) throws Exception {
String json = HttpUtils.getHttpClientResult(response);
Gson gson = new Gson();
Map<String, Object> map = gson.fromJson(json, HashMap.class);
return map;
}