HttpWebRequest BeginGetResponse not working - c#

I'm trying use HttpWebRequest, and my BeginGetRequestStream works but it never enters the BeginGetResponse function and i have no idea why.. i've searched for a couple of hours and have not found a solution that works
public void Initialize(IScheduler scheduler)
{
if(_isCloud)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_cloudMappingServer + "/Mapping/GetAllCentralPoints");
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.BeginGetRequestStream(new AsyncCallback(ReleaseReadCallback), request);
// Instruct the thread to wait until we resume it
_waitHandle.WaitOne();
_waitHandle.Dispose();
}
}
private void ReleaseReadCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest httpRequest = (HttpWebRequest)asynchronousResult.AsyncState;
using (Stream postStream = httpRequest.EndGetRequestStream(asynchronousResult))
{
using (MemoryStream memStream = new MemoryStream())
{
string queryString = string.Empty;
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(queryString);
memStream.Write(bytes, 0, bytes.Length);
memStream.Position = 0;
byte[] tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, 0, tempBuffer.Length);
postStream.Write(tempBuffer, 0, tempBuffer.Length);
}
}
httpRequest.BeginGetResponse(new AsyncCallback(ReleaseResponseCallback), httpRequest);
}
catch (Exception ex)
{
var test = ex;
}
}
private void ReleaseResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest responseRequest = (HttpWebRequest)asynchronousResult.AsyncState;
string responseString = string.Empty;
try
{
using (HttpWebResponse resp = (HttpWebResponse)responseRequest.EndGetResponse(asynchronousResult))
{
using (StreamReader streamRead = new StreamReader(resp.GetResponseStream()))
{
responseString = streamRead.ReadToEnd();
try
{
JsonSerializerSettings settings = new JsonSerializerSettings();
List<CentralPointViewModel> _allCentralPointViewModel = JsonConvert.DeserializeObject<List<CentralPointViewModel>>(responseString, settings);
}
catch (JsonReaderException)
{
responseString = responseString.Replace('\"'.ToString(), string.Empty);
string[] responseArray = responseString.Split(';');
}
catch (JsonSerializationException)
{
responseString = responseString.Replace('\"'.ToString(), string.Empty);
}
}
}
}
catch (Exception ex)
{
}
}
It never enters the ReleaseResponseCallback function! I am able to make my server call but the response never reaches me or I am not properly receiving it.. Any help is appreciated

Related

C# Why am I getting an out of memory exception when uploading large files?

I'm reading a large file into a stream, of which I'm filling a 4k buffer which I'm writing to a HttpWebRequest stream.
For some reason I'm getting out of memory exceptions, not sure why.
Am I doing something incorrectly?
My method:
public void StreamBlob(FileInfo file, Uri blobContainerSasUri, string containerName)
{
try
{
var method = "PUT";
var token = blobContainerSasUri.Query;
var requestUri =
new Uri($"https://{blobContainerSasUri.Host}/{containerName}/{string.Concat(file.Name, token)}");
using (var fileStream = file.OpenRead())
{
var request = (HttpWebRequest) WebRequest.Create(requestUri);
request.Method = method;
request.ContentType = MimeMapping.GetMimeMapping(file.FullName);
request.Headers.Add("x-ms-blob-type", "BlockBlob");
request.ContentLength = fileStream.Length;
request.AllowWriteStreamBuffering = false;
using (var serverStream = request.GetRequestStream())
{
var buffer = new byte[4096];
while (true)
{
var bytesRead = fileStream.Read(buffer, 0, buffer.Length);
if (bytesRead > 0)
serverStream.Write(buffer, 0, bytesRead);
else
break;
}
}
using (var resp = (HttpWebResponse) request.GetResponse())
{
try
{
if (resp.StatusCode == HttpStatusCode.OK)
_logger.Log.Info("Received http response {resp}");
}
catch (Exception ex)
{
_logger.Log.Warn($"Received http response {resp}", ex)
}
}
}
}
catch (Exception ex)
{
_logger.Log.Warn($"Error uploading {file.Fullname}, ex")
}

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);
}

The server committed a protocol violation. Section=ResponseHeader Detail='Content-Length' header value is invalid

When I try to communicate with wallet-qt using C#, I got this error and don't know what I missing. I also try a lot solution from google but not succesfull Please help me thank.
Here is my code that I got an idea from this topichere: https://bitcoin.stackexchange.com/questions/5810/how-do-i-call-json-rpc-api-using-c/5811#5811?newreg=e26b1cb9e4b24ebdac98193efb5d3f4b
static void Main(string[] args)
{
var ret = InvokeMethod("getblockhash", 15);
}
public static JObject InvokeMethod(string a_sMethod, params object[] a_params)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://localhost:9998");
webRequest.Credentials = new NetworkCredential("user", "pass");
webRequest.ContentType = "application/json-rpc";
webRequest.Method = "POST";
JObject joe = new JObject();
joe["jsonrpc"] = "1.0";
joe["id"] = "1";
joe["method"] = a_sMethod;
if (a_params != null)
{
if (a_params.Length > 0)
{
JArray props = new JArray();
foreach (var p in a_params)
{
props.Add(p);
}
joe.Add(new JProperty("params", props));
}
}
string s = JsonConvert.SerializeObject(joe);
// serialize json for the request
byte[] byteArray = Encoding.UTF8.GetBytes(s);
webRequest.ContentLength = byteArray.Length;
try
{
using (Stream dataStream = webRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
}
catch (WebException we)
{
//inner exception is socket
//{"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 23.23.246.5:8332"}
throw;
}
WebResponse webResponse = null;
try
{
using (webResponse = webRequest.GetResponse())
{
using (Stream str = webResponse.GetResponseStream())
{
using (StreamReader sr = new StreamReader(str))
{
return JsonConvert.DeserializeObject<JObject>(sr.ReadToEnd());
}
}
}
}
catch (WebException webex)
{
using (Stream str = webex.Response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(str))
{
var tempRet = JsonConvert.DeserializeObject<JObject>(sr.ReadToEnd());
return tempRet;
}
}
}
catch (Exception)
{
throw;
}
}

How to stream speech to wit.ai speech end point

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;
}
}

c# Webrequest Post and GetResponse

I am writing a program that will submit a XML to a website. The code written works fine, but sometimes it just stops working for some reason, throwing a
System.Net.ProtocolViolationException. I can close the program and re-run - it starts working again just fine.
Here is the code that I am using:
private string Summit(string xml)
{
string result = string.Empty;
StringBuilder sb = new StringBuilder();
try {
WebRequest request = WebRequest.Create(this.targetUrl);
request.Timeout = 800 * 1000;
RequestState requestState = new RequestState(xml);
requestState.Request = request;
request.ContentType = "text/xml";
// Set the 'Method' property to 'POST' to post data to a Uri.
requestState.Request.Method = "POST";
requestState.Request.ContentType = "text/xml";
// Start the Asynchronous 'BeginGetRequestStream' method call.
IAsyncResult r = (IAsyncResult)request.BeginGetRequestStream(new AsyncCallback(ReadCallBack), requestState);
// Pause the current thread until the async operation completes.
// Console.WriteLine("main thread waiting...");
allDone.WaitOne();
// Assign the response object of 'WebRequest' to a 'WebResponse' variable.
WebResponse response = null;
try {
response =request.GetResponse();
} catch (System.Net.ProtocolViolationException ex) {
response = null;
request.Abort();
request = null;
requestState = null;
return "";
}
//Console.WriteLine("The string has been posted.");
//Console.WriteLine("Please wait for the response...");
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
Char[] readBuff = new Char[256];
int count = streamRead.Read(readBuff, 0, 256);
//StringBuilder sb = new StringBuilder();
while (count > 0) {
String outputData = new String(readBuff, 0, count);
sb.Append(outputData);
count = streamRead.Read(readBuff, 0, 256);
}
// Close the Stream Object.
streamResponse.Close();
streamRead.Close();
//allDone.WaitOne();
// Release the HttpWebResponse Resource.
response.Close();
//return sb.ToString();
} catch (WebException webex) {
Debug.WriteLine(webex.Message);
} catch (System.Web.Services.Protocols.SoapException soapex) {
Debug.WriteLine(soapex.Message);
} catch (System.Net.ProtocolViolationException ex) {
Debug.WriteLine(ex.Message);
} catch (Exception ex) {
Debug.WriteLine(ex.Message);
}
return sb.ToString();
}
private static void ReadCallBack(IAsyncResult asyncResult)
{
try {
RequestState myRequestState = (RequestState)asyncResult.AsyncState;
WebRequest myWebRequest2 = myRequestState.Request;
// End of the Asynchronus request.
Stream responseStream = myWebRequest2.EndGetRequestStream(asyncResult);
//Convert the string into a byte array.
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] ByteArray = encoder.GetBytes(myRequestState.Xml);
// Write data to the stream.
responseStream.Write(ByteArray, 0, myRequestState.Xml.Length);
responseStream.Close();
} catch (WebException e) {
Console.WriteLine("\nReadCallBack Exception raised!");
Console.WriteLine("\nMessage:{0}", e.Message);
Console.WriteLine("\nStatus:{0}", e.Status);
}
allDone.Set();
}
response =request.GetResponse() is when it fails and gives an error
You must provide a request body if you set ContentLength>0 or
SendChunked==true. Do this by calling [Begin]GetRequestStream before
[Begin]GetResponse.
Any help would be greatly appreciated.
This gets tricky since we're doing async calls.
Do this in the following order:
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request)
Then in 'GetRequestStreamCallback(IAsyncResult asynchronousResult)' call:
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request)
Lastly, in the GetResponse, be sure to close the stream:
response.Close();
allDone.Set();
MSDN Does a really good job explaining it: http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetrequeststream.aspx

Categories

Resources