C# 400 Bad Request


#1

Hello everyone.

I am using HoloLens and I am creating an application of OpenALPR by using Unity C#.
I created the following script, but I got an error.

" 400 Bad Request"

Please tell me the solution.
Best regards.


using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using UnityEngine.UI;
using HoloToolkit.Unity.InputModule;
using UnityEngine.VR.WSA.WebCam;
using System.Linq;
using System.Text;
using System.IO;
using UnityEngine.Networking;

public class ImageToVisionAPI : MonoBehaviour, IInputClickHandler
{

public string openalpr_url = "https://api.openalpr.com/v2/recognize_bytes?recognize_vehicle=1&country=jp&secret_key=";
public string apiKey = "*****************************************";

public string fileName { get; private set; }
string responseData;

public float timeOut;
private float timeElapsed;

public Text text;
public FeatureType featureType = FeatureType.FACE_DETECTION;
public int maxResults = 10;

public GameObject ImageFrameObject;
public Text textObject;
PhotoCapture photoCaptureObject = null;

[System.Serializable]
public class AnnotateImageRequests
{
    public List<AnnotateImageRequest> requests;
}

[System.Serializable]
public class AnnotateImageRequest
{
    public Image image;
    public List<Feature> features;
}

[System.Serializable]
public class Image
{
    public string content;
}

[System.Serializable]
public class Feature
{
    public string type;
    public int maxResults;
}

[System.Serializable]
public class ImageContext
{
    public LatLongRect latLongRect;
    public List<string> languageHints;
}

[System.Serializable]
public class LatLongRect
{
    public LatLng minLatLng;
    public LatLng maxLatLng;
}

[System.Serializable]
public class AnnotateImageResponses
{
    public List<AnnotateImageResponse> responses;
}

[System.Serializable]
public class AnnotateImageResponse
{
    public List<FaceAnnotation> faceAnnotations;
    public List<EntityAnnotation> landmarkAnnotations;
    public List<EntityAnnotation> logoAnnotations;
    public List<EntityAnnotation> labelAnnotations;
    public List<EntityAnnotation> textAnnotations;
}

[System.Serializable]
public class FaceAnnotation
{
    public BoundingPoly boundingPoly;
    public BoundingPoly fdBoundingPoly;
    public List<Landmark> landmarks;
    public float rollAngle;
    public float panAngle;
    public float tiltAngle;
    public float detectionConfidence;
    public float landmarkingConfidence;
    public string joyLikelihood;
    public string sorrowLikelihood;
    public string angerLikelihood;
    public string surpriseLikelihood;
    public string underExposedLikelihood;
    public string blurredLikelihood;
    public string headwearLikelihood;
}

[System.Serializable]
public class EntityAnnotation
{
    public string mid;
    public string locale;
    public string description;
    public float score;
    public float confidence;
    public float topicality;
    public BoundingPoly boundingPoly;
    public List<LocationInfo> locations;
    public List<Property> properties;
}

[System.Serializable]
public class BoundingPoly
{
    public List<Vertex> vertices;
}

[System.Serializable]
public class Landmark
{
    public string type;
    public Position position;
}

[System.Serializable]
public class Position
{
    public float x;
    public float y;
    public float z;
}

[System.Serializable]
public class Vertex
{
    public float x;
    public float y;
}

[System.Serializable]
public class LocationInfo
{
    LatLng latLng;
}

[System.Serializable]
public class LatLng
{
    float latitude;
    float longitude;
}

[System.Serializable]
public class Property
{
    string name;
    string value;
}

public enum FeatureType
{
    TYPE_UNSPECIFIED,
    FACE_DETECTION,
    LANDMARK_DETECTION,
    LOGO_DETECTION,
    LABEL_DETECTION,
    TEXT_DETECTION,
    SAFE_SEARCH_DETECTION,
    IMAGE_PROPERTIES
}

public enum LandmarkType
{
    UNKNOWN_LANDMARK,
    LEFT_EYE,
    RIGHT_EYE,
    LEFT_OF_LEFT_EYEBROW,
    RIGHT_OF_LEFT_EYEBROW,
    LEFT_OF_RIGHT_EYEBROW,
    RIGHT_OF_RIGHT_EYEBROW,
    MIDPOINT_BETWEEN_EYES,
    NOSE_TIP,
    UPPER_LIP,
    LOWER_LIP,
    MOUTH_LEFT,
    MOUTH_RIGHT,
    MOUTH_CENTER,
    NOSE_BOTTOM_RIGHT,
    NOSE_BOTTOM_LEFT,
    NOSE_BOTTOM_CENTER,
    LEFT_EYE_TOP_BOUNDARY,
    LEFT_EYE_RIGHT_CORNER,
    LEFT_EYE_BOTTOM_BOUNDARY,
    LEFT_EYE_LEFT_CORNER,
    RIGHT_EYE_TOP_BOUNDARY,
    RIGHT_EYE_RIGHT_CORNER,
    RIGHT_EYE_BOTTOM_BOUNDARY,
    RIGHT_EYE_LEFT_CORNER,
    LEFT_EYEBROW_UPPER_MIDPOINT,
    RIGHT_EYEBROW_UPPER_MIDPOINT,
    LEFT_EAR_TRAGION,
    RIGHT_EAR_TRAGION,
    LEFT_EYE_PUPIL,
    RIGHT_EYE_PUPIL,
    FOREHEAD_GLABELLA,
    CHIN_GNATHION,
    CHIN_LEFT_GONION,
    CHIN_RIGHT_GONION
};

public enum Likelihood
{
    UNKNOWN,
    VERY_UNLIKELY,
    UNLIKELY,
    POSSIBLE,
    LIKELY,
    VERY_LIKELY
}

// Use this for initialization
void Start()
{
    InputManager.Instance.PushFallbackInputHandler(gameObject);
}

// Update is called once per frame
void Update()
{
    timeElapsed += Time.deltaTime;

    if (timeElapsed >= timeOut)
    {
        // Do anything
        timeElapsed = 0.0f;
    }
}

IEnumerator GetVisionFromImages()
{

    Debug.Log("GetVisionFromImages start!");

    if (apiKey == null || apiKey == "")
        Debug.LogError("No API key. Please set your API key into the \"Web Cam Texture To Cloud Vision(Script)\" component.");

    // translate to base64
    byte[] bytes = File.ReadAllBytes(fileName);
    string base64 = Convert.ToBase64String(bytes);
    textObject.text = fileName;
    var headers = new Dictionary<string, string>() {
        { "Content-Type", "application/json;" }
    };

    AnnotateImageRequests requests = new AnnotateImageRequests();
    requests.requests = new List<AnnotateImageRequest>();

    AnnotateImageRequest request = new AnnotateImageRequest();
    request.image = new Image();
    request.image.content = base64;
    request.features = new List<Feature>();

    Feature feature = new Feature();
    feature.type = this.featureType.ToString();
    feature.maxResults = this.maxResults;

    request.features.Add(feature);

    requests.requests.Add(request);

    string jsonData = JsonUtility.ToJson(requests, false);
    if (jsonData != string.Empty)
    {
        // Analize by OpenALPR
        string url = this.openalpr_url + this.apiKey;
        byte[] postData = System.Text.Encoding.UTF8.GetBytes(jsonData);

        using (WWW www = new WWW(url, postData, headers))
        {
            yield return www;
            if (www.error == null)
            {
                responseData = www.text;
                Debug.Log("GetEmotionFromImages finished!");
                Debug.Log(responseData.Replace("\n", "").Replace(" ", ""));
                AnnotateImageResponses responses = JsonUtility.FromJson<AnnotateImageResponses>(responseData);
                textObject.text = responseData;
            }
            else
            {
                Debug.Log("Error: " + www.error);
            }
        }
    }

}

// Air Tap
public void OnInputClicked(InputClickedEventData eventData)
{
    textObject.text = "Camera capturing...";
    PhotoCapture.CreateAsync(false, OnPhotoCaptureCreated);

}

public void DisplayImage()
{
    Texture2D imageTxtr = new Texture2D(2, 2);
    string fileName = gameObject.GetComponent<ImageToVisionAPI>().fileName;
    byte[] fileData = File.ReadAllBytes(fileName);
    imageTxtr.LoadImage(fileData);
    ImageFrameObject.GetComponent<Renderer>().material.mainTexture = imageTxtr;
}


void OnPhotoCaptureCreated(PhotoCapture captureObject)
{
    // Camera caputuing
    photoCaptureObject = captureObject;

    Resolution cameraResolution = PhotoCapture.SupportedResolutions.OrderByDescending((res) => res.width * res.height).First();

    CameraParameters c = new CameraParameters();
    c.hologramOpacity = 0.0f;
    c.cameraResolutionWidth = cameraResolution.width;
    c.cameraResolutionHeight = cameraResolution.height;
    c.pixelFormat = CapturePixelFormat.NV12;

    captureObject.StartPhotoModeAsync(c, OnPhotoModeStarted);
}

private void OnPhotoModeStarted(PhotoCapture.PhotoCaptureResult result)
{
    if (result.success)
    {
        // save file
        fileName = string.Format(@"CapturedImage{0}_n.jpg", Time.time);
        fileName = Path.Combine(Application.temporaryCachePath, fileName);
        Debug.LogFormat("filePath={0}", fileName);
        photoCaptureObject.TakePhotoAsync(fileName, PhotoCaptureFileOutputFormat.JPG, OnCapturedPhotoToDisk);

    }
    else
    {
        Debug.LogError("Unable to start photo mode!");
    }
}

void OnCapturedPhotoToDisk(PhotoCapture.PhotoCaptureResult result)
{
    if (result.success)
    {
        // After saving, analyze
        Debug.Log("Saved Photo to disk!");
        textObject.text = "Saved Photo to disk!";
        StartCoroutine(GetVisionFromImages());
        photoCaptureObject.StopPhotoModeAsync(OnStoppedPhotoMode);
        DisplayImage();
    }
    else
    {
        Debug.Log("Failed to save Photo to disk");
    }
}

void OnStoppedPhotoMode(PhotoCapture.PhotoCaptureResult result)
{
    photoCaptureObject.Dispose();
    photoCaptureObject = null;
}

}