1

I would like to write a class in c# which should send an HTTP request (post) to a PHP file which is on my server in order to retrieve a json object.

This is the code I've got:

   public void SendRequest(){
    HttpWebRequest request = (HttpWebRequest)
        WebRequest.Create("url");

    // execute the request
    HttpWebResponse response = (HttpWebResponse)
        request.GetResponse();
    }

Is that what I need? What do you think I should change or improve? Thank you for your help.

1
  • So where do you set the verb to POST ? Commented Apr 19, 2013 at 23:03

1 Answer 1

1

You need to post data and read the response:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("url");
string yourPostData = "Your post data";
string sreverResponseText;

byte[] postDataBytes = Encoding.UTF8.GetBytes(yourPostData);
request.ContentLength = yourPostData.Length;
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";

using (Stream requestStream = request.GetRequestStream())
      requestStream.Write(postDataBytes, 0, postDataBytes.Length);

using (response = (HttpWebResponse)request.GetResponse())
      using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
            sreverResponseText = streamReader.ReadToEnd();

Now what you are looking for is in sreverResponseText, also you can access headers from response.Headers.ToString()

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.