C# Uploading file to HTTPServer - c#

I need to write a httpclient to upload a huge file to the server using http. The code
public Stream function()
{
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;
request.Method = "POST";
// Get the request stream.
Stream dataStream = request.GetRequestStream ();
// Write the data to the request stream.
return dataStream;
}
Then, I return the dataStream to the caller of this function so that the application keeps writing to the stream using write. Then once done with the writing, GetResponse is called and then the stream is closed. But I get the exception
ProtocolViolationException
at System.Net.HttpWriteStream.Write() while writing to the stream.
Kindly help.

Have you considered using Fiddler to debug the process when using a browser? This is a simple proxy allowing you to inspect http traffic.

The ProtocolViolationException is probably thrown because the request method is GET or HEAD.
You must set the Method to POST like this:
// Set the 'Method' property of the 'Webrequest' to 'POST'.
request.Method = "POST";
See HttpWebRequest.GetRequestStream Method documentation on MSDN.

Related

Yammer deny request programmatically

Is there a way to reject pending request programmatically, well i don't see any api for that so any yammer expert our there to help?
From Chrome developer tools I see this is the request send by Yammer UI.
https://www.yammer.com/****/join_requests/968249/deny
Code we have used:
WebRequest request = WebRequest.Create("https://www.yammer.com/****/join_requests/968249/deny");
request.Method = "POST";
string postData = "userId=" + userId;
byte[] byteArray = System.Text.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;
request.Headers.Add(HttpRequestHeader.Authorization, yammerToken);
// 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();
Error: 404 not found, its obv the api is not there so any solution
Please find the image
There isn't a supported API for doing this.

Why am I not recieving a response from the webrequest?

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

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;

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