从wit.ai统一得到错误的请求错误

时间:2017-09-16 07:19:42

标签: c# unity3d wit.ai

我在WebRequest中设置了这些东西

 HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.wit.ai/speech");

        request.Method = "POST";
        request.Headers ["Authorization"] = "Bearer " + token;
        request.ContentType = "audio/wav";
        request.ContentLength = BA_AudioFile.Length;

但我仍然收到此错误

WebException: The remote server returned an error: (400) Bad Request.
System.Net.HttpWebRequest.CheckFinalStatus (System.Net.WebAsyncResult result)
System.Net.HttpWebRequest.SetResponseData (System.Net.WebConnectionData data)

我已经从here匹配了我的请求格式。在提出请求时,我不知道我遗失了哪些东西。我正在使用Unity游戏引擎。 请记住我正在使用this wit3d project from github

如评论所示,这是完整的代码

using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
using SimpleJSON;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
// using System.Web;

public partial class Wit3D : MonoBehaviour {

    // Class Variables

    // Audio variables
    public AudioClip commandClip;
    int samplerate;

    // API access parameters
    string url;
    string token;
    UnityWebRequest wr;

    // Movement variables
    public float moveTime;
    public float yOffset;

    // GameObject to use as a default spawn point
    public GameObject spawnPoint;

    // Use this for initialization
    void Start () {

        // If you are a Windows user and receiving a Tlserror
        // See: https://github.com/afauch/wit3d/issues/2
        // Uncomment the line below to bypass SSL
        // System.Net.ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => { return true; };

        // set samplerate to 16000 for wit.ai
        samplerate = 16000;

    }

    // Update is called once per frame
    void Update () {

        if (Input.GetKeyDown (KeyCode.Space)) {
            print ("Listening for command");
            commandClip = Microphone.Start(null, false, 10, samplerate);  //Start recording (rewriting older recordings)
        }


        if (Input.GetKeyUp (KeyCode.Space)) {

            // Debug
            print("Thinking ...");

            // Save the audio file
            Microphone.End(null);
            SavWav.Save("sample", commandClip);

            // At this point, we can delete the existing audio clip
            commandClip = null;

            //Grab the most up-to-date JSON file
            // url = "https://api.wit.ai/message?v=20160305&q=Put%20the%20box%20on%20the%20shelf";
            token = "mytoken";// "NJP2HHQXIUK3IGW53WXL65NRD74GGJ5B";

            //Start a coroutine called "WaitForRequest" with that WWW variable passed in as an argument
            string witAiResponse = GetJSONText("Assets/sample.wav");
            print (witAiResponse);
            Handle (witAiResponse);
        }


    }
    public bool MyRemoteCertificateValidationCallback(System.Object sender,
    X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        bool isOk = true;
        // If there are errors in the certificate chain,
        // look at each error to determine the cause.
        if (sslPolicyErrors != SslPolicyErrors.None)
        {
            for (int i = 0; i < chain.ChainStatus.Length; i++)
            {
                if (chain.ChainStatus[i].Status == X509ChainStatusFlags.RevocationStatusUnknown)
                {
                    continue;
                }
                chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
                chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
                chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
                chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags;
                bool chainIsValid = chain.Build((X509Certificate2)certificate);
                if (!chainIsValid)
                {
                    isOk = false;
                    break;
                }
            }
        }
        return isOk;
    }

    string GetJSONText(string file) {

        // get the file w/ FileStream
        FileStream filestream = new FileStream (file, FileMode.Open, FileAccess.Read);
        BinaryReader filereader = new BinaryReader (filestream);
        byte[] BA_AudioFile = filereader.ReadBytes ((Int32)filestream.Length);
        filestream.Close ();
        filereader.Close ();
        ServicePointManager.ServerCertificateValidationCallback = MyRemoteCertificateValidationCallback;
        // create an HttpWebRequest
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.wit.ai/speech");

        request.Method = "POST";
        request.Headers ["Authorization"] = "Bearer " + token;
        request.ContentType = "audio/wav";
        request.ContentLength = BA_AudioFile.Length;

        request.GetRequestStream ().Write(BA_AudioFile, 0, BA_AudioFile.Length);

        // Process the wit.ai response
        //try
        //{
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK)
            {
                print("Http went through ok");
                StreamReader response_stream = new StreamReader(response.GetResponseStream());
                return response_stream.ReadToEnd();
            }
            else
            {
                return "Error: " + response.StatusCode.ToString();
                return "HTTP ERROR";
            }
        //}
        //catch (Exception ex)
        //{
            //return "Error: " + ex.Message;
            return "HTTP ERROR";
        //}       
    }

}

令人惊讶的是,它正确地运行了与日志不同的时间。 enter image description here

它通常会给出错误 enter image description here

0 个答案:

没有答案