How to stream speech to wit.ai speech end point - c#

I'm having trouble getting a good response from wit.ai's speech end point. The response is always 400. I seem to be following the docs but something's wrong.
Any help would be appreciated.
private string ProcessSpeechStream(Stream stream)
{
BinaryReader filereader = new BinaryReader(stream);
byte[] arr = filereader.ReadBytes((Int32)stream.Length);
filereader.Close();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.wit.ai/speech");
request.SendChunked = true;
request.Method = "POST";
request.Headers["Authorization"] = "Bearer " + APIToken;
request.ContentType = "chunked";
request.ContentLength = arr.Length;
var st = request.GetRequestStream();
st.Write(arr, 0, arr.Length);
st.Close();
// Process the wit.ai response
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
StreamReader response_stream = new StreamReader(response.GetResponseStream());
return response_stream.ReadToEnd();
}
else
{
Logger.AILogger.Log("Error: " + response.StatusCode.ToString());
return string.Empty;
}
}
catch (Exception ex)
{
Logger.AILogger.Log("Error: " + ex.Message, ex);
return string.Empty;
}
}

This code sample uses the correct encoding. If you are using Naudio make sure you waveformat is like the encoding (Plus it has to be mono):
private string ProcessSpeechStream(Stream stream)
{
var ms = new MemoryStream();
stream.CopyTo(ms);
var arr = ms.ToArray();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.wit.ai/speech");
request.SendChunked = true;
request.Method = "POST";
request.Headers["Authorization"] = "Bearer " + APIToken;
request.ContentType = "audio/raw;encoding=signed-integer;bits=16;rate=44100;endian=little";
request.ContentLength = arr.Length;
var st = request.GetRequestStream();
st.Write(arr, 0, arr.Length);
st.Close();
// Process the wit.ai response
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
StreamReader response_stream = new StreamReader(response.GetResponseStream());
return response_stream.ReadToEnd();
}
}
catch (Exception ex)
{
// use your own exception handling class
// Logger.AILogger.Log("Error: " + ex.Message, ex);
return string.Empty;
}
}

Related

Why POST use Webrequest always fail but use html form is success?

I spent two days to debug but I can't find error's cause.
App client using WebRequest call servlet result is fail, WebException is "The operation has time out" but When I call servlet by POST method in html form is success. Here is code C#:
public string PostURLRequest(string URL, string postData)
{
try
{
System.Text.Encoding enc =
System.Text.Encoding.GetEncoding("shift_jis");
byte[] postDataBytes = System.Text.Encoding.ASCII.GetBytes(postData);
System.Net.HttpWebRequest req =
(System.Net.HttpWebRequest)System.Net.WebRequest.Create(URL);
req.ProtocolVersion = System.Net.HttpVersion.Version10;
req.Method = "POST";
req.ReadWriteTimeout = -1;
req.KeepAlive = false;
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postDataBytes.Length;
req.Timeout = 10*60*1000;
System.IO.Stream reqStream = req.GetRequestStream();
reqStream.Write(postDataBytes, 0, postDataBytes.Length);
reqStream.Close();
System.Net.WebResponse res = req.GetResponse();//----------> THROW EXCEPTION HERE
System.IO.Stream resStream = res.GetResponseStream();
System.IO.StreamReader sr = new System.IO.StreamReader(resStream, enc);
String text = sr.ReadToEnd();
sr.Close();
return text;
}
catch(System.Net.WebException ex)
{
if (ex.Status == System.Net.WebExceptionStatus.Timeout)
{
Console.WriteLine("Error: {0}", ex.Message);
}
return "NG";
}
}

I am trying to write a console app in c# that consume a web service running on tomcat, to perform a "PUT" method with an xml file

public static String TransferMessage(String uri, String resource,
String xml_data, Method httpmethod,
ReturnType returnType)
{
try
{
WebRequest request = WebRequest.Create(uri + resource);
request.Method = httpmethod.ToString();
request.ContentType = #"application/xml;";
//request.Headers.Add("Token", token);
request.Timeout = Convert.ToInt32((new TimeSpan(1, 0, 0)).TotalMilliseconds);
request.ContentLength = Encoding.UTF8.GetByteCount(xml_data);
if (httpmethod != Method.GET)
using (Stream stream = request.GetRequestStream())
{
stream.Write(Encoding.UTF8.GetBytes(xml_data), 0,
Encoding.UTF8.GetByteCount(xml_data));
stream.Flush();
stream.Close();
}
return getResponseContent(request.GetResponse());
}
catch(Exception e)
{
Console.WriteLine(e);
}
return null;
}
Main method:
var res_xml = MethodHelper.TransferMessage(endpoint, "/" + resource,xml,
MethodHelper.Method.PUT,
MethodHelper.ReturnType.XML);
I am getting this error
ERROR javax.xml.bind.UnmarshalException\n - with
linked exception:\n[org.xml.sax.SAXParseException; line Number: 1;
columnNumber: 1; Content is not allowed in prolog.]
try{
string contend = "";
using (var streamReader = new StreamReader(new FileInfo(#"C:\Users\absmbez\Desktop\temp\upload.xml").OpenRead()))
{
contend = streamReader.ReadToEnd();
}
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
webrequest.Method = "PUT";
webrequest.ContentType = "application/xml";
Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
byte[] requestData = enc.GetBytes(contend);
webrequest.ContentLength = requestData.Length;
using (var stream = webrequest.GetRequestStream())
{
stream.Write(requestData, 0, requestData.Length);
}
HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
StreamReader responseStream = new StreamReader(webresponse.GetResponseStream(), enc);
string result = string.Empty;
result = responseStream.ReadToEnd();
webresponse.Close();
return result;
}
catch (Exception e)
{
Console.WriteLine(e);
}

C# REST API Authenticate with Bearer Token

Trying to write a tool which downloads a .zip file from a server via REST API.
It works without any problems with SOAP-UI but my tool doesn't want to download any files.
Always getting this error:
Cannot send a content-body with this verb-type.
My POST-Requests work fine but GET-Requests make problems. I Think there is a problem with my Webrequest-Header.
The authentication has to look like this:
Bearer "Access Token"
Here is my code:
class RestProvider
{
protected string method;
protected string endpoint;
protected string resource;
protected string parameters;
public RestProvider(string method, string endpoint, string resource, string parameters)
{
this.method = method;
this.endpoint = endpoint;
this.resource = resource;
this.parameters = parameters;
}
public string GetResponse()
{
string resultString = string.Empty;
ASCIIEncoding enc = new ASCIIEncoding();
byte[] paramData = enc.GetBytes(parameters);
if (this.method == "post")
{
try
{
WebRequest request = WebRequest.Create(this.endpoint + this.resource);
request.Method = this.method;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = paramData.Length;
Stream stream = request.GetRequestStream();
stream.Write(paramData, 0, paramData.Length);
stream.Close();
WebResponse response = request.GetResponse();
stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
resultString = sr.ReadToEnd();
sr.Close();
stream.Close();
}
catch(Exception ex)
{
resultString = "{\"errorMessages\":[\"" + ex.Message.ToString() + "\"],\"errors\":{}}";
}
}
else if(this.method == "get")
{
try
{
WebRequest request = WebRequest.Create(this.endpoint + this.resource);
request.Headers["Authorization"] = "Bearer " + Convert.ToBase64String(Encoding.Default.GetBytes(this.parameters));
request.Method = this.method;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = paramData.Length;
Stream stream = request.GetRequestStream();
stream.Write(paramData, 0, paramData.Length);
stream.Close();
WebResponse response = request.GetResponse();
stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
resultString = sr.ReadToEnd();
sr.Close();
stream.Close();
}
catch (Exception ex)
{
resultString = "{\"errorMessages\":[\"" + ex.Message.ToString() + "\"],\"errors\":{}}";
}
}
return resultString;
}
}
Any ideas?

How to shim HttpWebRequest Headers?

I am trying to Shim the following code:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
request.Headers.Add("Authorization", "Bearer " + authToken.token.access_token);
request.Accept = "application/json";
But running the Unit Test throws an exception in this part: request.Headers.Add() because request.Headers is null. This, in spite of initializing Headers in my test:
ShimHttpWebRequest request = new ShimHttpWebRequest();
ShimWebRequest.CreateString = (urio) => {
request.Instance.Headers = new WebHeaderCollection {
{"Authorization", "Bearer abcd1234"}
};
//also tried initilizing it like this:
//WebHeaderCollection headers = new WebHeaderCollection();
//headers[HttpRequestHeader.Authorization] = "Bearer abcd1234";
//request.Instance.Headers = headers;
return request.Instance;
};
But request.Instance.Headers is still null.
What am I missing?
I solved this by creating a getter for Headers so that it would return a WebHeaderCollection instead of null.
ShimHttpWebRequest request = new ShimHttpWebRequest();
ShimWebRequest.CreateString = (urio) => request.Instance;
request.HeadersGet = () => {
WebHeaderCollection headers = new WebHeaderCollection();
headers.Add("Authorization", "Bearer abcd1234");
return headers;
};
I solved this by instantiating Header property of ShimHttpWebRequest as follows,
var httpWebRequest = new ShimHttpWebRequest() { HeadersGet = () => new WebHeaderCollection() };
ShimWebRequest.CreateString = (arg1) => httpWebRequest.Instance;
This is my code, you can try it:
public static string HttpPostWebRequest(string requestUrl, int timeout, string requestXML, bool isPost, string encoding, out string msg)
{
msg = string.Empty;
string result = string.Empty;
try
{
byte[] bytes = System.Text.Encoding.GetEncoding(encoding).GetBytes(requestXML);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
request.ContentType = "application/x-www-form-urlencoded";
request.Referer = requestUrl;
request.Method = isPost ? "POST" : "GET";
request.ContentLength = bytes.Length;
request.Timeout = timeout * 1000;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
if (responseStream != null)
{
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding(encoding));
result = reader.ReadToEnd();
reader.Close();
responseStream.Close();
request.Abort();
response.Close();
return result.Trim();
}
}
catch (Exception ex)
{
msg = ex.Message + ex.StackTrace;
}
return result;
}

ReCaptcha Post Using C# in MVC Application

I'm trying to do a direct post to Google using this code. I keep getting an error, "invalid private key". I have double checked it and even had someone else double check it. The reason i'm going it this way is because I'm using javascript and ajax to pass the variables to this function.
[HttpPost]
public string ValidateReCaptcha(string captchaChallenge, string captchaResponse)
{
if (captchaChallenge != null && captchaResponse != null)
{
string strPrivateKey = System.Web.Configuration.WebConfigurationManager.AppSettings["recaptchaPrivateKey"].ToString();
string strParameters = "?privatekey=" + strPrivateKey +
"&remoteip=" + HttpContext.Request.UserHostAddress.ToString() +
"&challenge=" + captchaChallenge +
"&response=" + captchaResponse;
WebRequest request = WebRequest.Create("http://www.google.com/recaptcha/api/verify");
request.Method = "POST";
string postData = strParameters;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
if (responseFromServer.ToString() != "true")
{
errorCodeList.Add(8);
return responseFromServer + strPrivateKey;
}
else
{
return responseFromServer;
}
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
}
else
{
errorCodeList.Add(8);
return null;
}
}
The "return" in the IF/ELSE means thet that the "Clean up the streams" code is unreachable and as the return withing the IF would end the execution, this could be simplified a little:
[HttpPost]
public string ValidateReCaptcha(string captchaChallenge, string captchaResponse)
{
if (captchaChallenge != null && captchaResponse != null)
{
// original code, remains unchanged
/*
...snipped for clarity
*/
// Clean up the streams (relocated to make it reachable code)
reader.Close();
dataStream.Close();
response.Close();
if (responseFromServer.ToString() != "true")
{
errorCodeList.Add(8);
return responseFromServer + strPrivateKey; // "IF" ends execution here
}
return responseFromServer; // "ELSE" ends execution here
}
errorCodeList.Add(8);
return null;
}
I guess you need to delete ? on post data.
I've changed the code for me, and this works
private bool ValidarCaptcha(UsuarioMV usuarioMV)
{
Stream dataStream = null;
WebResponse response = null;
StreamReader reader = null;
try
{
string captchaChallenge = usuarioMV.sCaptchaChallenge;
string captchaResponse = usuarioMV.sCaptchaResponse;
if (captchaChallenge != null
&& captchaResponse != null)
{
throw new Exception("Parametros captcha nulos.");
}
WebRequest request = WebRequest.Create("https://www.google.com/recaptcha/api/verify");
request.Method = "POST";
//Solicitud
string strPrivateKey = System.Web.Configuration.WebConfigurationManager.AppSettings["RecaptchaPrivateKey"].ToString();
NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(String.Empty);
outgoingQueryString.Add("privatekey", strPrivateKey);
outgoingQueryString.Add("remoteip", "localhost");
outgoingQueryString.Add("challenge", captchaChallenge);
outgoingQueryString.Add("response", captchaResponse);
string postData = outgoingQueryString.ToString();
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
//Respuesta
dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
response = request.GetResponse();
dataStream = response.GetResponseStream();
reader = new StreamReader(dataStream);
if (reader.ReadLine() != "true")
{
string sLinea = reader.ReadLine();
//if the is another problem
if (sLinea != "incorrect-captcha-sol")
{
throw new Exception(sLinea);
}
return false;
}
else
{
return true;
}
}
catch (Exception ex)
{
throw;
}
finally
{
//Clean up the streams.
if (reader != null)
reader.Close();
if (dataStream != null)
dataStream.Close();
if (response != null)
response.Close();
}
}
You can try like this basically. I got affirmative result !!!
public async Task<bool> ReCaptcha(Recaptcha recaptcha)
{
string secretKey = "YOUR_PRIVATE_KEY";
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsync(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secretKey, recaptcha.Response), null);
if (response.IsSuccessStatusCode)
{
var resultString = await response.Content.ReadAsStringAsync();
RecaptchaResponse resp = JsonConvert.DeserializeObject<RecaptchaResponse>(resultString);
if (resp.success)
{
return true;
}
}
return false;
}

Categories

Resources