zoukankan      html  css  js  c++  java
  • 异步请求类HttpClient

    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);
                }
            }
        }
    }
  • 相关阅读:
    MySQL监控全部执行过的sql语句
    Linux之网络编程:时间服务器
    人生哲理 |南怀瑾最经典的50句话
    TCP/IP协议(一)网络基础知识 网络七层协议
    Linux下进程通信之管道
    一个完整的项目管理流程
    Linux编程之select
    (笔记)电路设计(十四)之放大器的应用
    ds18b20采集温度并上报服务器
    java中基于swing库自定义分页组件
  • 原文地址:https://www.cnblogs.com/ncore/p/2799204.html
Copyright © 2011-2022 走看看