如何使用 JAVA 将本地图像而不是 URL 发送到 Microsoft Cognitive Face API

Gan*_*uri 5 java microsoft-cognitive

我正在尝试使用 Microsoft Cognitive Services 的 Face API。我想知道如何通过 rest API 调用将本地图像发送到 Face API 并使用JAVA从中请求结果。任何人都可以帮我解决这个问题吗?

Microsoft 在其网站上提供的测试选项仅采用 URL,我尝试将我的本地路径转换为 ​​URL 并将其作为输入,但这不起作用。

小智 1

一种选择是使用该类FileEntity

// This sample uses the Apache HTTP client from HTTP Components (http://hc.apache.org/httpcomponents-client-ga/)
import java.io.File;
import java.net.URI;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class Face
{
    public static void main(String[] args) 
    {
        HttpClient httpclient = HttpClients.createDefault();

        try
        {
            URIBuilder builder = new URIBuilder("https://api.projectoxford.ai/face/v1.0/detect");

            builder.setParameter("returnFaceId", "true");

            URI uri = builder.build();
            HttpPost request = new HttpPost(uri);
            request.setHeader("Ocp-Apim-Subscription-Key", "YOUR_KEY");


            // Request body
            File file = new File("YOUR_FILE");
            FileEntity reqEntity = new FileEntity(file, "application/octet-stream");
            request.setEntity(reqEntity);

            HttpResponse response = httpclient.execute(request);
            HttpEntity entity = response.getEntity();

            if (entity != null) 
            {
                System.out.println(EntityUtils.toString(entity));
            }
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)