Feedback

C# - Simple Web-Request with Web-Response

Veröffentlicht von am 30.08.2006
(3 Bewertungen)
Sample to build a simple Web-Request with a simple Server-Web-Response interpretation
//Create a Web-Request to an URL
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.microsoft.com/en/us/default.aspx");

//Defined poperties for the Web-Request
httpWebRequest.Method = "POST";
httpWebRequest.MediaType = "HTTP/1.1";
httpWebRequest.ContentType = "text/xml";
httpWebRequest.UserAgent = "Example Client";

//Defined data for the Web-Request
byte[] byteArrayData = Encoding.ASCII.GetBytes("A string you would like to send");
httpWebRequest.ContentLength = byteArrayData.Length;

//Attach data to the Web-Request
Stream dataStream = httpWebRequest.GetRequestStream();
dataStream.Write(byteArrayData, 0, byteArrayData.Length);
dataStream.Close();

//Send Web-Request and receive a Web-Response
HttpWebResponse httpWebesponse = (HttpWebResponse)httpWebRequest.GetResponse();

//Translate data from the Web-Response to a string
dataStream = httpWebesponse.GetResponseStream();
StreamReader streamreader = new StreamReader(dataStream, Encoding.UTF8);
string response = streamreader.ReadToEnd();
streamreader.Close();

4 Kommentare zum Snippet

Timo Boehme schrieb am 03.03.2008:
Where is SR_DataStream declared? Wo ist SR_DataStream deklariert?
Linoge schrieb am 03.03.2008:
Ich habe den Snippet verbessert.
Christian R. schrieb am 08.08.2010:
I understand the "Defined data for the Web-Request" as the possibility to send GET or POST parameters. But a var_dump() of the $_SERVER on my Apache doesn't show me the sent data. Might I understand the data stream wrong or there is something wrong with the code?
Christian R. schrieb am 09.08.2010:
Problem solved. The dataStream is appended as raw post data an can be read server side with $HTTP_RAW_POST_DATA.
 

Logge dich ein, um hier zu kommentieren!