Mustafa Akıllı Mustafa Akıllı - 2 months ago 17
Java Question

Microsoft Cognitive Services Face API Error for Java Create a Person Group

This code for Create a Person Group with Java.

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.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

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

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


URI uri = builder.build();
HttpPut request = new HttpPut(uri);
request.setHeader("Content-Type", "application/json");
request.setHeader("Ocp-Apim-Subscription-Key", "mysubscriptionkey");


// Request body
StringEntity reqEntity = new StringEntity("{body}");
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());
}
}
}


When I run this code, I take the this error:


{"error":{"code":"BadArgument","message":"Request body is invalid."}}


What can I do for fix it. I didn't find the sample for Create a Person Group with java on the internet, so I can't fix it.

Answer

As the error suggests, the HTTP request body is malformed as {body}.

Please take a look at the API page, under the section labeled Request body. You are required to provide a name, and can optionally add user data.

StringEntity reqEntity = new StringEntity("{" +
    "\"name\":\"group1\"," +
    "\"userData\":\"user-provided data attached to the person group\""+
"}") 

You can find some additional Java examples on the GitHub SDK page.