I am using Jon Skeet's ReadFully method implemented here:
public static byte[] ReadFully(Stream stream)
{
var buffer = new byte[32768];
using (var ms = new MemoryStream())
{
while (true)
{
int read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write(buffer, 0, read);
}
}
}
It throws an exception at the line:
int read = stream.Read(buffer, 0, buffer.Length);
The error message is The request was aborted: The connection was closed unexpectedly.
I am sending an xml request to a webservice. My send method looks like this:
private static string SendRequest(XElement request, string url)
{
var req = (HttpWebRequest)WebRequest.Create(url);
req.ContentType = "application/soap+xml;";
req.Method = "POST";
req.KeepAlive = false;
req.Timeout = System.Threading.Timeout.Infinite;
req.ReadWriteTimeout = System.Threading.Timeout.Infinite;
req.ProtocolVersion = HttpVersion.Version10;
req.AllowWriteStreamBuffering = false;
using (var stm = req.GetRequestStream())
{
using (var stmw = new StreamWriter(stm))
{
stmw.Write(request.ToString());
}
}
Stream responseStream;
using (var webResponse = req.GetResponse())
{
responseStream = webResponse.GetResponseStream();
}
// Do whatever you need with the response
var myData = ReadFully(responseStream);
string responseString = Encoding.ASCII.GetString(myData);
return responseString;
}
I tried without and without the following variables set and it gives me the same message:
req.KeepAlive = false;
req.Timeout = System.Threading.Timeout.Infinite;
req.ReadWriteTimeout = System.Threading.Timeout.Infinite;
req.ProtocolVersion = HttpVersion.Version10;
req.AllowWriteStreamBuffering = false;
The problem is in this part of your code:
// wrong way to do it!
Stream responseStream;
using (var webResponse = req.GetResponse())
{
responseStream = webResponse.GetResponseStream();
}
// Do whatever you need with the response
var myData = ReadFully(responseStream);
You're disposing your response object before reading from its stream. Try something like this instead:
byte[] myData;
using (var webResponse = req.GetResponse())
{
var responseStream = webResponse.GetResponseStream();
myData = ReadFully(responseStream); // done with the stream now, dispose of it
}
// Do whatever you need with the response
string responseString = Encoding.ASCII.GetString(myData);
Related
While I am doing a web API using C# console Application using HttpWebRequest an exception occurs
The remote server returned an error: (500) Internal Server Error.
Here is my code:
string postURL = "";
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(postURL);
webRequest.Method = "POST";
webRequest.Headers.Add("token", "ee22c61a55bd0629c8c8a63a8c8b73ed");
webRequest.KeepAlive = true;
webRequest.ContentType = "application/json";
webRequest.Headers.Add("ContentType","application/json");
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int byteCount = 0;
FileInfo finfo = new FileInfo(#"D:\audio\smallwave.zip");
webRequest.ContentLength = finfo.Length;
// webRequest.SendChunked = true;
using (FileStream fileStream = File.OpenRead(#"D:\audio\smallwave.zip"))
using (Stream requestStream = webRequest.GetRequestStream())
{
while ((byteCount = fileStream.Read(buffer, 0, bufferSize)) > 0)
{
requestStream.Write(buffer, 0, byteCount);
}
}
HttpWebResponse httpResponse = (HttpWebResponse)webRequest.GetResponse();
// using (WebResponse response = webRequest.GetResponse())
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
String result = streamReader.ReadToEnd();
Console.WriteLine(result);
}
An error is showing like
An unhandled exception of type 'System.Net.WebException' occurred in
System.dll
Additional information: The remote server returned an error: (500)
Internal Server Error.
using HTTPClient
string baseUrl = "https://vspark-demo.vocitec.com/transcribe/M2ComSys-Pilot/eng1CCStereo/";
HttpClient client = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
HttpContent content = new StringContent("file");
HttpContent DictionaryItems = new FormUrlEncodedContent(new[] {
new KeyValuePair<string, string>("token", "ee22c61a55bd0629c8c8a63a8c8b73ed"),
});
form.Add(content, "files");
// form.Add(DictionaryItems, "data");
form.Add(new StringContent("ee22c61a55bd0629c8c8a63a8c8b73ed"), "token");
var stream = new FileStream(#"D:\audio\variety.wav", FileMode.Open);
content = new StreamContent(stream);
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "file",
FileName = "variety.wav"
};
form.Add(content);
HttpResponseMessage response = null;
try
{
response = (client.PostAsync(baseUrl, form)).Result;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine(response);
var k = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(k);
Console.ReadLine();
}
I'm trying to get some data back from rest WS in C# but I'm getting this error:
You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.
This is the code I'm trying to use:
var json = new JavaScriptSerializer().Serialize(order);
string jsonResponseToString = "";
HttpWebRequest request =
(HttpWebRequest)WebRequest.Create("https://myurl.com");
request.Method = "POST";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(json);
request.ContentLength = byteArray.Length;
request.ContentType = #"application/json";
try
{
using (var response = (HttpWebResponse)request.GetResponse())
{
Stream str = response.GetResponseStream();
var sr = new StreamReader(str, encoding);
jsonResponseToString = sr.ReadToEnd();
var result = new OrderResult();
result = new JavaScriptSerializer().Deserialize<OrderResult>(jsonResponseToString);
if (str != null)
{
str.Flush();
str.Close();
}
}
}
catch (WebException ex)
{
//
}
The error is happening on this line:
using (var response = (HttpWebResponse)request.GetResponse())
How can I solve this, am I doing something wrong?
As the error is trying to tell you, you need to write your bytes to the request before you can send it.
Call GetRequestStream() and write your bytes.
I'm trying to submit an attachment to a REST API. attachment is not submitted correctly. I believe that i'm doing something wrong with the request
RunQueryimage("http://www.extremetech.com/wp-content/uploads/2012/12/Audi-A1.jpg);
public string RunQueryimage(string imagePath)
{
//do get request
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create("https://iss.ontimenow.com/api/v2/incidents/");
request.ContentType = "application/octet-stream";
request.Method = "POST";
var webClient = new WebClient();
byte[] bytearr = webClient.DownloadData(imagePath);
var filecontent = new ByteArrayContent(bytearr);
// request.ContentLength = 0;
if (filecontent != null)
{
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(filecontent);
}
}
HttpWebResponse response = (HttpWebResponse)
request.GetResponse();
string result = string.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
return result;
}
You already have a stream open when you create a web request.
Change this:
byte[] bytearr = webClient.DownloadData(imagePath);
var filecontent = new ByteArrayContent(bytearr);
// request.ContentLength = 0;
if (filecontent != null)
{
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(filecontent);
}
}
To:
byte[] fileContent = webClient.DownloadData(imagePath);
if (fileContent != null)
{
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContent, 0, fileContent.Length);
requestStream.Close();
}
I get warning on responseStream in following function:
private static string GetResponseString(WebResponse response)
{
using (var responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
using (var responseReader = new StreamReader(responseStream))
{
var strResponse = responseReader.ReadToEnd();
return strResponse;
}
}
}
return string.Empty;
}
I call this function from places like like this one:
var request = (HttpWebRequest)WebRequest.Create(Uri);
request.Headers.Add("Authorization", "GoogleLogin auth=" + this.SecurityToken);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.Timeout = 5000;
// build the post string
var postString = new StringBuilder();
postString.AppendFormat("registration_id={0}", recipientId);
postString.AppendFormat("&data.payload={0}", message);
postString.AppendFormat("&collapse_key={0}", collapseKey);
// write the post-string as a byte array
var requestData = Encoding.ASCII.GetBytes(postString.ToString());
request.ContentLength = requestData.Length;
var requestStream = request.GetRequestStream();
requestStream.Write(requestData, 0, requestData.Length);
requestStream.Close();
// Do the actual request and read the response stream
try
{
var response = request.GetResponse();
var responseString = GetResponseString(response);
response.Close();
return responseString.Contains("id=")
? SendStatus.Ok
: GetSendStatusFromResponse(responseString);
}
catch (WebException ex)
{
var webResponse = (HttpWebResponse)ex.Response;
if (webResponse != null)
{
if (webResponse.StatusCode.Equals(HttpStatusCode.Unauthorized))
{
return SendStatus.Unauthorized;
}
if (webResponse.StatusCode.Equals(HttpStatusCode.ServiceUnavailable))
{
return SendStatus.ServiceUnavailable;
}
}
this.LoggerService.Log(null, ex);
return SendStatus.GeneralException;
}
StreamReader takes ownership of the stream passed to it in the constructor call in the sense that it will call Dispose on it when the StreamReader itself is closed - hence it will already be disposed when the outer Using statement attempts to dispose of it.
Here's my code for Request and Response.
System.IO.MemoryStream xmlStream = null;
HttpWebRequest HttpReq = (HttpWebRequest)WebRequest.Create(url);
xmlStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(format));
byte[] buf2 = xmlStream.ToArray();
System.Text.UTF8Encoding UTF8Enc = new System.Text.UTF8Encoding();
string s = UTF8Enc.GetString(buf2);
string sPost = "XMLData=" + System.Web.HttpUtility.UrlDecode(s);
byte[] bPostData = UTF8Enc.GetBytes(sPost);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
HttpReq.Timeout = 30000;
request.Method = "POST";
request.KeepAlive = true;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bPostData, 0, bPostData.Length);
requestStream.Close();
}
string responseString = "";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
responseString = sr.ReadToEnd();
}
No part of this code crashes. The "format" string is the one with XML in it. By the end when you try to see what's in the responseString, it's an empty string. I am supposed to see the XML sent back to me from the URL. Is there something missing in this code?
I would recommend a simplification of this messy code:
using (var client = new WebClient())
{
var values = new NameValueCollection
{
{ "XMLData", format }
};
byte[] resultBuffer = client.UploadValues(url, values);
string result = Encoding.UTF8.GetString(resultBuffer);
}
and if you wanted to upload the XML directly in the POST body you shouldn't be using application/x-www-form-urlencoded as content type. You probably should specify the correct content type, like this:
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "text/xml";
var data = Encoding.UTF8.GetBytes(format);
byte[] resultBuffer = client.UploadData(url, data);
string result = Encoding.UTF8.GetString(resultBuffer);
}