Why am I not recieving a response from the webrequest? - c#

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

Related

Stream CanRead/CanSeek false + Length&Position threw exception NotSupportedException

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
}

C# HttpWebRequest.Write does not send content

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;

Performing requests using WebRequest and a Stream

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.

How to login to the android market using C#?

I would like to login to the webpage Android Market using C#. I spent the whole day reading about HTTP requests and POST data, but nothing seems to work. What I can do is read the webpage that holds the google login form. But reading the page AFTER the login seems impossible...
Can anyone give me a hint on how to do this?
BTW: The code I've tried is shown below:
string mail = "XXXXXXXXXX#gmail.com";
string pw = "XXXXXXXXXX";
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create (#"https://market.android.com/publish");
// 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 ("Email={0}&Passwd={1}&signIn=Sign+in", mail, pw);
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 ();
What I usually do: get live http headers for firefox and you can record the request your browser sends. Then simply repeat that in code.
for example, the android marketplace does it pretty different from your code.
it actually posts to: https://accounts.google.com/ServiceLoginAuth
And posts the data continue=https%3A%2F%2Fmarket.android.com%2Fpublish%2FHome&followup=https%3A%2F%2Fmarket.android.com%2Fpublish%2FHome&service=androiddeveloper&nui=1&dsh=&GALX=&pstMsg=1&dnConn=&timeStmp=&secTok=&Email=Passwd=&signIn=
You need to create a CookieContainer instance and assign it to the CookieContainer property in each request.
This will store the login cookie so that the site knows that you're still logged in.

finding c# ways to send http requests

I am trying to develop a Microsoft excel plugin to send excel sheet data to a web application. It will require the plugin to prompt username and password and then send login http request to the web application to get a session . Then it will upload data to the web application . What .net things should I use ?
Post Method Sample for send username and password. for uploading file just search "File Upload C#" in google.com or bing.com or try C#'s WebClient.UploadFile, Code Project
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("http://example.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 = "username=user&passsword=pass";
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();
For HTTP communication in .NET, try System.Net.WebClient or System.Net.HttpWebRequest.

Categories