I am new to this and what am i trying to do is POST a image as byte array to a URL, but i get error when i try to get the response.
Here is the code from MSDN:
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create(BASE_URL);
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
byte[] byteArray = fileContent; // my image as bytearray
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse(); // here it stops
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
While debugging in Stream, CanRead and CanSeek is false,Length and Position both throw same error:
'((System.Net.ConnectStream)dataStream).Length' threw an exception of
type 'System.NotSupportedException'.
I tried copying to a memory stream, but same problem. Nothing that i found on internet helped me solve this.
In regards to debugging
This is normal behavior from a NetworkStream
The NetworkStream does not support random access to the network data
stream. The value of the CanSeek property, which indicates whether the
stream supports seeking, is always false; reading the Position
property, reading the Length property, or calling the Seek method will
throw a NotSupportedException.
In regards to your MSDN Example
see WebRequest.GetResponse
The notes state
If a WebException is thrown, use the Response and Status properties of
the exception to determine the response from the server.
Although there are lots of ways to use WebRequest
It would be worth while wrapping this in a try catch and working out what the actual exception is and what its telling you
try
{
WebResponse response = request.GetResponse();
...
...
}
catch(WebException ex)
{
// inspect Response and Status properties
}
Related
So i'm trying to learn how WebRequest & WebResponse works.
So far it seems a bit like when you create a TcpClient and listener and make them connect and then send a buffer inbetween them.
However this seems to be a bit different.
So what im doing here is that im making a request to a website, in this case Spotify (Thought I would try to login to spotify as my first project).
Using the POST method to post data to the website.
converting my string to a byteArray
changing the contenttype (Not really sure if im doing it right here, not 100% sure what the values can be)
and the length of the content is the length of the byteArray
I create a stream of data in which I will get the stream from the request.
and then I proceed to write the byteArray starting from the offset of 0 and then the length of the thing that im going to write.
then I close the dataStream.
Now I create a WebResponse (which will get the response to tell me if everything is okay or not (im assuming))
Then I print out the the statusdescription (It doesnt print out anything here not sure why)
Then I create a stream that contains the content from the server
and then I create a streamreader which will read the content..
The rest is pretty straight forward.
Issue
So the issue is that its not printing out anything to the console and I am not sure why. How do I make it print out?
ERROR
So I caught the exception and this is what img etting
"The remote server returned an error: <405> Method not allowed."
CODE
class Program
{
static void Main(string[] args)
{
Console.Title = "Login Test";
Console.ForegroundColor = ConsoleColor.Green;
tester();
Console.ReadLine();
}
private static void tester()
{
try
{
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("https://accounts.spotify.com/en-SK/login");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
}
catch { }
}
}
Trying to send a web request with some body content. The important part is that I need some data in the body of the post request. My understanding of how to do this is to open a WebRequestStream, and then write the bytes to it, then to close it. This is supposed to be simple. Here is my code:
HttpWebRequest request;
request = (HttpWebRequest)WebRequest.Create("http://localhost:50203/api/Values");//
request.Method = "POST";
byte[] requestBody = ASCIIEncoding.ASCII.GetBytes(HttpUtility.UrlEncode("grant_type=client_credentials"));
Stream requestBodyStream = request.GetRequestStream();
requestBodyStream.Write(requestBody, 0, requestBody.Length);
requestBodyStream.Flush();
requestBodyStream.Close();
WebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
myString = reader.ReadToEnd();
But the RequestBodyStream.Write method is not sending anything in the body. I know this because I'm running the server side program at the other end.
I also tried to do this with a StreamWriter instead of using a byte stream, and I get the same result. No matter how I do it, there is no content in the body.
My understanding is that closing the stream is what sends the actual data. I also tried adding a Flush() method to the stream.
Why is this method not producing any body?
Add 'ContentType' and 'ContentLength' headers to the request instance:
request.ContentType = "application/json"; // Or whatever you want
request.ContentLength = requestBody.Length;
public class MyWebRequest
{
private WebRequest request;
private Stream dataStream;
private string status;
public String Status
{
get
{
return status;
}
set
{
status = value;
}
}
public MyWebRequest(string url)
{
// Create a request using a URL that can receive a post.
request = WebRequest.Create(url);
}
public MyWebRequest(string url, string method)
: this(url)
{
if (method.Equals("GET") || method.Equals("POST"))
{
// Set the Method property of the request to POST.
request.Method = method;
}
else
{
throw new Exception("Invalid Method Type");
}
}
public MyWebRequest(string url, string method, string data)
: this(url, method)
{
// Create POST data and convert it to a byte array.
string postData = data;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
}
public string GetResponse()
{
// Get the original response.
WebResponse response = request.GetResponse();
this.Status = ((HttpWebResponse)response).StatusDescription;
// Get the stream containing all content returned by the requested server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content fully up to the end.
string responseFromServer = reader.ReadToEnd();
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
}
I saw this code and was analyzing it. I searched for the WebRequest class at msdn and understood it, but I don't understand why I have to use a Stream to perform the requests. I don't know what a stream is, and why it is needed. Can somebody help me? Also, can somebody explain to me the following two lines?
// Get the request stream.
dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
The stream gets data, and then I write data to the stream, not the WebRequest object?
Thanks.
The GetRequestStream is used to initiate send data to internet resources.
Also it used to return stream instance for sending data to internet resources.
To communicate with an HTTP server, you need to make an HTTP request (examples). Now you actually send that request as a series of bytes via a Stream. A stream is really just a series of bytes.
Most I/O operations (including files or network sockets) are buffered. That means you put bytes in a buffer repeatedly, and when that buffer gets full enough, it is actually sent. The stream is really just an abstraction for that. So really you are only sending bytes over the network in those two lines.
From MSDN "Provides a generic view of a sequence of bytes". I Stream is an abstraction of various objects you might want to read or write data from. Specific examples are FileStream for reading and writing to disk, and a MemoryStream. Take a look at the other types that inherit from Stream.
The two lines you highlight are how you send data in the WebRequest. Imagine an HTTP request, when you make the request some data is sent to the server. When You're using a WebRequest you write this data by getting the request stream and writing bytes to it.
There is a page in remote web-site, where one can enter input values in forms, click a button and get a result in output form.
I want to send a request to the page with filling necessary input forms, submit it and get a result page with output form filled.
All threads with similar topics give the code samples like this:
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("http://www.site.com");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = string.Format("inputParam=value");
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
response.Close();
It returns a page with filled input forms, but output field is still blank, like it doesn't do a commit button click.
How can I do a commit from my C# code and receive an html document with output data?
Change the webresponse section to the following;
WebResponse response = request.GetResponse ();
dataStream = response.GetResponseStream ();
StreamReader reader = new StreamReader (dataStream);
string responseFromServer = reader.ReadToEnd ();
I have a client application running on C# on a .NETCF 3.5 device POSTing to a Java servlet located remotely. I am receiving a "Request Timed out" during my third HTTP POST to the same servlet. For example, if the servlet manages login to our Java server, the first two login attempts from the client would go through (same client device) and when I attempt the third one, it will return in a "Request timed out" exception from the server. I have noticed this happen always and I can't figure out the problem. I read that C# by default sends the Request 100 continue in the HTTP headers so I used the ServicePointManager to set the request 100 to false to no avail.
Here is the code that is throwing this error:
serverUrl = url;
string responseFromServer = "";
try
{
System.Net.ServicePointManager.Expect100Continue = false;
int tmp = ServicePointManager.DefaultConnectionLimit;
// Create a request using a URL that can receive a post.
request = (HttpWebRequest)WebRequest.Create(url);
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(url);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
request.Timeout = (50 * 100);
request.Proxy = System.Net.GlobalProxySelection.GetEmptyWebProxy();
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
response = (HttpWebResponse)request.GetResponse();
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
responseFromServer = reader.ReadToEnd();
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
catch (Exception WebExp)
{
Logging.Instance.Log(Logging.Levels.Error, "Error in DoPost while retrieving : "+url+ " " + WebExp.Message.ToString());
Logging.Instance.Log(Logging.Levels.Error, WebExp.StackTrace.ToString());
throw WebExp;
}
Any help would be much appreciated. Thanks!
This behaviour is due to wrong Exception handling regarding to the WebResponse. You have always to handle the response and close it. Otherwise the third attempt of HTTP Webrequest will fail with timeout which is limited by WinCE.
Following source code will be safe:
HttpWebResponse response = null;
try
{
//...
response = (HttpWebResponse)request.GetResponse();
//...
}
catch(Exception e)
{
// logging, etc.
throw e;
}
finally
{
if(response!=null)
{
response.Close();
}
}