How can i get cookies in web request using c#? - c#

I'm new to c# language. I want to write this code to post data to web url:
byte[] data = Encoding.ASCII.GetBytes($"Identifier={"anyUsername"}&Password={"Password"}");
WebRequest request = WebRequest.Create("http://users.tclnet.ir/Authentication/LogOn");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
string responseContent = null;
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader sr99 = new StreamReader(stream))
{
responseContent = sr99.ReadToEnd();
}
}
}
but i want get cookies from that answer,how can i write code to achieve it?

Related

Calling WebRequest with Endpoint generate 591

Hello I am trying to call a webservice that is running on my machine and when I call it without the endpoint everything run fine, when I add the endpoint give me an error 591 returned by the webserver, this is my code:
var request = (HttpWebRequest)WebRequest.Create("http://localhost:8111/fiscal");
request.Method = "POST";
request.ContentLength = 0;
request.ContentType = "application/x-www-form-urlencoded";
request.Host = "localhost:8111";
var encoding = new UTF8Encoding();
var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(JsonConvert.SerializeObject(formData));
request.ContentLength = bytes.Length;
using (var writeStream = request.GetRequestStream())
{
writeStream.Write(bytes, 0, bytes.Length);
}
using (var response = (HttpWebResponse)request.GetResponse())
{
var responseValue = string.Empty;
if (response.StatusCode != HttpStatusCode.OK)
{
var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
throw new ApplicationException(message);
}
// grab the response
using (var responseStream = response.GetResponseStream())
{
if (responseStream != null)
using (var reader = new StreamReader(responseStream))
{
responseValue = reader.ReadToEnd();
}
}
MessageBox.Show(responseValue);
}

Send an HTTP POST request with C#

I'm try to Send Data Using the WebRequest with POST But my problem is No data has be streamed to the server.
string user = textBox1.Text;
string password = textBox2.Text;
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "username" + user + "&password" + password;
byte[] data = encoding.GetBytes(postData);
WebRequest request = WebRequest.Create("http://localhost/s/test3.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
Stream stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
WebResponse response = request.GetResponse();
stream = response.GetResponseStream();
StreamReader sr99 = new StreamReader(stream);
MessageBox.Show(sr99.ReadToEnd());
sr99.Close();
stream.Close();
here the result
It's because you need to assign your posted parameters with the = equal sign:
byte[] data = Encoding.ASCII.GetBytes(
$"username={user}&password={password}");
WebRequest request = WebRequest.Create("http://localhost/s/test3.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
string responseContent = null;
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader sr99 = new StreamReader(stream))
{
responseContent = sr99.ReadToEnd();
}
}
}
MessageBox.Show(responseContent);
See the username= and &password= in post data formatting.
You can test it on this fiddle.
Edit :
It seems that your PHP script has parameters named diffently than those used in your question.

Stream does not support reading when placing a HTTP Post request

I am facing an error that is "Stream does not support reading". I am placing a Http post request to the url. Below is my code that what i am using
var request = (HttpWebRequest) WebRequest.Create("https://test.com/Hotel Hospitality Source?method=fetchInfo");
var postData = "&username=testing";
postData += "&password=Testing";
postData += "&hotelId=h075-103";
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using(var ms = new MemoryStream())
request.GetRequestStream().CopyTo(ms);
var response = (HttpWebResponse) request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
Firstly I have used below code.
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
I am getting error when I am using CopyTo method for stream. How can I resolve this error?
What is using (var ms=new MemoryStream()) request.GetRequestStream().CopyTo(ms); supposed to do? You're trying to copy the request stream (which is write-only) into a new memorystream that you then dispose.
You need to write into the request stream:
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}

Get html source from internet meet some issue

I want to fetch a web page to analyze stock information. I use the following sample code to get html data using c#. While it compiles, running it always ends in an error.
The following is my sample code:
string urlAddress = "http://pchome.syspower.com.tw/stock/sto0/ock2/sid2404.html";
var request = (HttpWebRequest)WebRequest.Create(urlAddress);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = 1414;
var requestStream = request.GetRequestStream();
requestStream.Write(Encoding.UTF8.GetBytes("is_check=1"), 0, 10);
requestStream.Close();
var response = (HttpWebResponse)request.GetResponse();
var sr = new StreamReader(response.GetResponseStream());
string rawData = sr.ReadToEnd();
sr.Close();
response.Close();
Does anyone know how to solve this issue?
The errors were mostly related to the order of your code and the closing of Stream objects your were still going to use.
Also I recommend to use using where possible to correctly dispose objects.
Use this code:
string rawData;
byte[] bytes = Encoding.UTF8.GetBytes("is_check=1");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bytes.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
rawData = sr.ReadToEnd();
}
}
}

How to ignore reponse data from when send Post request?

I send Post request by follow code:
try
{
string responseContent;
request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = cookieContainer;
// Set Method to "POST"
request.Method = "POST";
// Set the content type of the WebRequest
request.ContentType = "application/x-www-form-urlencoded";
request.Proxy = GlobalProxySelection.GetEmptyWebProxy();
request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3";
// Set the content length
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byteArray = encoding.GetBytes(requestCommand);
request.ContentLength = byteArray.Length;
// Get the request stream
using (Stream requestStream = request.GetRequestStream())
{
// Write the "POST" data to the stream
requestStream.Write(byteArray, 0, byteArray.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (BufferedStream buffer = new BufferedStream(responseStream))
{
using (StreamReader reader = new StreamReader(buffer))
{
responseContent = reader.ReadToEnd();
}
}
}
}
return responseContent;
}
catch (Exception ex)
{
return ex.Message;
}
}
It's works ok. But the code lines below is so slow.
using (StreamReader reader = new StreamReader(buffer))
{
responseContent = reader.ReadToEnd();
}
I don't know why! I have spend more time to find out solution, such at set proxy = null,... but no results.
Are there any way to ignore that line. I dont need to receive response data. I have tried replace that lines by:
using (Stream responseStream = response.GetResponseStream())
{
responseStream.Flush();
responseStream.Close();
}
But I can't send Post request correctly and sucessfuly. Please help me. Thanks so much!
If you don't care at all about the response or whether it fails, you can probably queue up the response on a new thread and just ignore it.
using (Stream requestStream = request.GetRequestStream())
{
// Write the "POST" data to the stream
requestStream.Write(byteArray, 0, byteArray.Length);
}
// now put the get response code in a new thread and immediately return
ThreadPool.QueueUserWorkItem((x) =>
{
using (var objResponse = (HttpWebResponse) request.GetResponse())
{
responseStream = new MemoryStream();
objResponse.GetResponseStream().CopyTo(responseStream);
responseStream.Seek(0, SeekOrigin.Begin);
}
});

Categories

Resources