I try to post an XML file to the url and get the response back. I have this code to post. I am not really sure how to check if it is posting correctly and how to get the response.
WebRequest req = null;
WebResponse rsp = null;
// try
// {
string fileName = #"C:\ApplicantApproved.xml";
string uri = "http://stage.test.com/partners/wp/ajax/consumeXML.php";
req = WebRequest.Create(uri);
req.Method = "POST"; // Post method
req.ContentType = "text/xml; encoding='utf-8'";
// Wrap the request stream with a text-based writer
StreamWriter writer = new StreamWriter(req.GetRequestStream());
// Write the XML text into the stream
writer.WriteLine(this.GetTextFromXMLFile(fileName));
writer.Close();
// Send the data to the webserver
rsp = req.GetResponse();
I think I should have response in rsp but I am not seeing anything usufull on it.
Please try following.
WebRequest req = null;
string fileName = #"C:\ApplicantApproved.xml";
string uri = "http://stage.test.com/partners/wp/ajax/consumeXML.php";
req = WebRequest.Create(uri);
req.Method = "POST"; // Post method
req.ContentType = "text/xml; encoding='utf-8'";
// Write the XML text into the stream
byte[] byteArray = Encoding.UTF8.GetBytes(this.GetTextFromXMLFile(fileName));
// Set the ContentLength property of the WebRequest.
req.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = req.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
WebResponse response = req.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();
try
req.ContentType = "application/xml";
Related
I need to implement an application to post string like HttpRequest to specify IP address and then receive answer in httpRespons form.
Here is code for sending
WebRequest request = WebRequest.Create("http://192.168.1.10");
request.Method = "POST";
string postData = "string I want to post";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
I'm not able to test this code. Is this code OK?
Here is code for receive answer:
WebResponse response = request.GetResponse();
richTextBox1.AppendText(((HttpWebResponse)response).StatusDescription);
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
richTextBox1.AppendText(responseFromServer);
reader.Close();
dataStream.Close();
response.Close();
Is this code OK?
The code is correct,but i think StreamReader reader = new StreamReader(dataStream); should append Encoding :StreamReader reader = new StreamReader(dataStream,encoding);
I have an application written in c#.NET 2.0 Windows app. I am trying to implement web crawler using HttpWebRequest & HttpWebResponse. In this application i am using both http get & post request for a third part web sites. this web site provides user account for its members.
i am trying to login this sites using positing data then entering into my profile page & then trying to make another GETrequest & then make another POST request with post data.
but i am not able to make successfull request .
it through an error
"The server committed a protocol violation. Section=ResponseHeader
Detail=Header name is invalid"
then i set <httpWebRequest useUnsafeHeaderParsing="true" /> in app.config files. after that
it throw an error The underlying connection was closed:
The connection was closed unexpectedly : System.Net.WebException.
anybody can tell me what the reason for showing this error
my code below.
request.CookieContainer = objContainer;
request.KeepAlive = true;
response = (HttpWebResponse)request.GetResponse();
dataStream = response.GetResponseStream();
reader = new StreamReader(dataStream);
strServerResponse = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
//=======================================================================
StringBuilder strLinkBuilder = new StringBuilder();
strLinkBuilder.Append("j_username=username");
strLinkBuilder.Append("&j_password=password");
request = (HttpWebRequest)HttpWebRequest.Create(strBaseURL + "j_security_check");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = strLinkBuilder.ToString();
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
request.KeepAlive = true;
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
for (int i = 0; i < response.Cookies.Count; i++)
{
response.Cookies[i].Path = String.Empty;
}
request.CookieContainer = objContainer;
request.CookieContainer.Add(response.Cookies);
// 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();
// 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.
reader = new StreamReader(dataStream);
// Read the content.
strServerResponse = reader.ReadToEnd();
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
//-------------------------------------------------------
request = (HttpWebRequest)HttpWebRequest.Create(strBaseURL + "ded/nsdlconsofile.xhtml");
//request.CookieContainer = objContainer;
request.KeepAlive = true;
// request.Method = "POST";
for (int i = 0; i < response.Cookies.Count; i++)
{
response.Cookies[i].Path = String.Empty;
}
request.CookieContainer = objContainer;
request.CookieContainer.Add(response.Cookies);
response = (HttpWebResponse)request.GetResponse();
dataStream = response.GetResponseStream();
reader = new StreamReader(dataStream);
strServerResponse = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
//-------------------------------------------------------
strLinkBuilder = new StringBuilder();
strLinkBuilder.Append("finYr=2012");
strLinkBuilder.Append("&qrtr=3");
strLinkBuilder.Append("&frmType=24Q");
strLinkBuilder.Append("&download_conso=Go");
strLinkBuilder.Append("&requestnsdlconsoForm_SUBMIT=1");
Dictionary<string, string> objNameval = TraceHiddenField(strServerResponse, "");
foreach (KeyValuePair<string, string> pair in objNameval)
{
strLinkBuilder.Append("&" + pair.Key + "=" + pair.Value);
}
request = (HttpWebRequest)HttpWebRequest.Create(strBaseURL + "ded/nsdlconsofile.xhtml");
// Set the Method property of the request to POST.
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.KeepAlive = false;
// request.ServicePoint.Expect100Continue = false;
request.UserAgent = "Mozilla/4.0 (compatible;)";
request.ProtocolVersion = HttpVersion.Version10;
// Create POST data and convert it to a byte array.
postData = strLinkBuilder.ToString();
byte[] byteData = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteData.Length;
for (int i = 0; i < response.Cookies.Count; i++)
{
response.Cookies[i].Path = String.Empty;
}
request.CookieContainer = objContainer;
request.CookieContainer.Add( response.Cookies);
// Get the request stream.
dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteData, 0, byteData.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.
reader = new StreamReader(dataStream);
strServerResponse = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
I am currently having a problem.
I am trying to post my data to a PHP document but it does not get the whole value.
Somewhere in the middle it stops posting.
Does anyone know where the problem is located?
The bytearray is 7401 long. That cant be to long rigth?
My code is below:
public string RecieveData(string url, string postData = "")
{
WebRequest request = WebRequest.Create(url);
// If required by the server, set the credentials.
NetworkCredential nc = new NetworkCredential("user", "pass");
Stream dataStream;
if (postData != "")
{
// 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.
dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
}
request.Credentials = nc;
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(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);
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
/*
}
catch (Exception)
{
MessageBox.Show("Er is iets fout gegaan met verbinden");
return "";
}
*/
}
7401 is not too long.
My guess is that the data you are posting are not fully URL-encoded, e.g. one of the characters in the byte array causes the PhP parser to stop. Make sure you are looking at the raw data (e.g. using Wireshark).
I'm trying to get the userID of a Facebook user, I already have the access_token and I use http request to do it. My simple problem is that : I want the user's id but my program just crash... I use WPF, C# Here is my little call :
var url = string.Format("https://graph.facebook.com/me?access_token=" + token + "&response_type=id");
var req = WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
string postData = "'access_token='" + token;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
var stream = req.GetRequestStream();
stream.Write(byteArray, 0, byteArray.Length);
stream.Close();
WebResponse response = req.GetResponse();
aTextBox.Text = ((HttpWebResponse)response).StatusDescription;
stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
Thanks!
Don't use Web Browser for this! You may use HttpWebRequest for that kind of things:
string url = "https://graph.facebook.com/me?access_token=" + token + "&response_type=id";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
Stream receiveStream = response.GetResponseStream ();
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
string responseData = readStream.ReadToEnd();
I want to reuse a WebRequest object so that cookies and session would be saved for later request to the server. Below is my code. If i use Post function twice on the second time at
request.ContentLength = byteArray.Length;
it will throw an exception
This property cannot be set after writing has started!
But as you can see
dataStream.Close();
Should close the writing process! Anybody knows what's going on?
static WebRequest request;
public MainForm()
{
request = WebRequest.Create("http://localhost/admin/admin.php");
}
static string Post(string url, string data)
{
request.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(data);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
reader.Close();
dataStream.Close();
response.Close();
request.Abort();
return responseFromServer;
}
You cannot reuse the WebRequest. Take the returned HttpWebResponse.Cookies, construct a new WebRequest and fill the HttpWebRequest.CookieContainer. (You need to assign a CookieContainer in the first request to get Cookies returned.)