非同期要求クラスHttpClient

5940 ワード

using System;

using System.Net;

using System.Windows;

using System.IO;



public class HttpClient

{

    private WebRequest webRequest = null;

    public delegate void ResponseEventHandler(String responseResult);

    public event ResponseEventHandler onResponseEventHandler;

    public delegate void RequestEventHandler();

    public event RequestEventHandler onRequestEventHandler;

    public string PostData { get; set; }



    public HttpClient(Uri clientUri)

    {

        Uri endpoint = clientUri;

        webRequest = WebRequest.Create(endpoint);

        webRequest.ContentType = "application/x-www-form-urlencoded";

        webRequest.Method = "POST";

    }



    public void Post()

    {

        webRequest.BeginGetRequestStream(new AsyncCallback(RequestReady), webRequest);

    }

    private void RequestReady(IAsyncResult asyncResult)

    {

        if (this.onRequestEventHandler != null)

        {

            this.onRequestEventHandler();

        }

        WebRequest request = asyncResult.AsyncState as WebRequest;

        Stream requestStream = request.EndGetRequestStream(asyncResult);



        using (StreamWriter writer = new StreamWriter(requestStream))

        {

            writer.Write(this.PostData);

            writer.Flush();

            writer.Close();

        }

        webRequest.BeginGetResponse(new AsyncCallback(ResponseReady), webRequest);

    }

    private void ResponseReady(IAsyncResult asyncResult)

    {

        if (this.onResponseEventHandler != null)

        {

            WebRequest request = asyncResult.AsyncState as WebRequest;

            WebResponse response = request.EndGetResponse(asyncResult);



            using (Stream responseStream = response.GetResponseStream())

            {

                String responseResult = String.Empty;

                try

                {

                    StreamReader reader = new StreamReader(responseStream);

                    responseResult = reader.ReadToEnd();

                }

                catch (WebException er)

                {

                    responseResult = er.Message;

                }

                catch (Exception er)

                {

                    responseResult = er.Message;

                }

                this.onResponseEventHandler(responseResult);

            }

        }

    }

}