Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a local image instead of URL to Microsoft Cognitive Face API using JAVA

Am trying to play with Face API of Microsoft Cognitive Services. Am wondering how to send a local image through rest API calls to Face API and request for the results from it using JAVA. Can anyone help me with this please?

The Testing opting provided by Microsoft on their site only takes URL, I Tried to convert my local path to URL and give it as input but that doesn't work.

like image 933
Ganesh Taduri Avatar asked Nov 09 '22 09:11

Ganesh Taduri


1 Answers

One option is to use the FileEntity class.

// 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());
        }
    }
}
like image 97
cthrash Avatar answered Nov 14 '22 21:11

cthrash