0

I'm making a little project using the Google Vision API. I want to detect the face of a base64 encoded image that a send to the API in a POST request. My code is based on this tutorial of Google: https://cloud.google.com/community/tutorials/make-an-http-request-to-the-cloud-vision-api-from-java. Apparently it is possible to send a base64 encoded image.

Here is my code:

    File File = new File(args[2]);
    String ImageString;

    FileInputStream fileInputStreamReader = new FileInputStream(File);
    byte[] bytes = new byte[(int)File.length()];
    fileInputStreamReader.read(bytes);
    ImageString = Base64.getEncoder().encodeToString(bytes);

    URL serverUrl = new URL(TARGET_URL + API_KEY); //TARGET_URL = "https://vision.googleapis.com/v1/images:annotate?"
    URLConnection urlConnection = serverUrl.openConnection();
    HttpURLConnection httpConnection = (HttpURLConnection)urlConnection;

    httpConnection.setRequestMethod("POST");
    httpConnection.setRequestProperty("Content-Type", "application/json");

    httpConnection.setDoOutput(true);

    BufferedWriter httpRequestBodyWriter = new BufferedWriter(new
            OutputStreamWriter(httpConnection.getOutputStream()));

    httpRequestBodyWriter.write
            ("{\"requests\":  [{ \"features\":  [ {\"type\": \"FACE_DETECTION\""
                    +"}], \"image\": {\"content\": \"" + ImageString + "\"}]}");
    httpRequestBodyWriter.close();

As you see, I replaced the "content" field by my string. I just don't know what I am doing wrong. Thanks in advance.

pm0733464
  • 2,862
  • 14
  • 16
  • What error are you getting? It seems your braces are not balanced so your content does not constitute a valid JSON, shouldn't it end with }}]} ? – JuniorDev Mar 23 '17 at 08:54
  • I had a bad request error, I forgot a "}". I thought I valided the JSON with JSONLint. It works now ! Thank you. – Anthony Marzolini Mar 23 '17 at 09:04

0 Answers0