Java API Example
This example uses General Table OCR as an example to describe how to use Java to call an API. To call other APIs, replace https://{endpoint}/v2/{project_id}/ocr/general-table in code with the actual one.
package OCRDemo;
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 OCRDemo {
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}/ocr/general-table";
String token = "Actual token value obtained by the user";
String imgPath = "./data/general-table-demo.png"; //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}/v2/{project_id}/ocr/general-table in this example. |
| 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 a token, see Getting Started. |
| imagePath | Image path. An image file path or image URL is supported. The URL can be an HTTP/HTTPS or OBS URL. |
Last Article: Python 3 API Example
Next Article: PHP API Example
Did this article solve your problem?
Thank you for your score!Your feedback would help us improve the website.