C# Programmation Réseau: Exécuter une requête POST d’un serveur HTTP

Author:
 

using System;
using System.Net;
using System.IO;
using System.Text;
using System.Threading;

class HttpWebRequestBeginGetRequest
{
    private static ManualResetEvent allDone = new ManualResetEvent(false);

    public static void Main(string[] args)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com");
        request.ContentType = "application/x-www-form-urlencoded";
        request.Method = "POST";
        request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
        allDone.WaitOne();
    }

    private static void GetRequestStreamCallback(IAsyncResult asynchronousResult)
    {
        HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
        Stream postStream = request.EndGetRequestStream(asynchronousResult);
        string postData = Console.ReadLine();
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        postStream.Write(byteArray, 0, postData.Length);
        postStream.Close();
        request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
    }

    private static void GetResponseCallback(IAsyncResult asynchronousResult)
    {
        HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
        Stream streamResponse = response.GetResponseStream();
        StreamReader streamRead = new StreamReader(streamResponse);
        string responseString = streamRead.ReadToEnd();
        Console.WriteLine(responseString);
        streamResponse.Close();
        streamRead.Close();
        response.Close();
        allDone.Set();
    }
}

   
  

Leave a Reply

Your email address will not be published. Required fields are marked *