Csharp:HttpWebRequest or HttpClient

        /// <summary>
        ///  Define other methods and classes here
        /// </summary>
        /// <param name="url"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static Task<string> MakeAsyncRequest(string contentType, string contenttxt, string mobile)
        {
            string url = "http://www.dusystem.com/UserServiceAPI";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = contentType;
            request.Method = WebRequestMethods.Http.Post; //get
            request.Timeout = 20000;
            request.Proxy = null;
            byte[] data = System.Text.Encoding.GetEncoding("gbk").GetBytes("geovindu"); //System.Text.UnicodeEncoding.ASCII.GetBytes("geovindu");//UTF8  
            Base64Encoder myEncoder = new Base64Encoder(data);
            StringBuilder sb = new StringBuilder();
            sb.Append(myEncoder.GetEncoded());
            string msg = UrlEncode(contenttxt);            
            string content = string.Format("method={0}&isLongSms={1}&username={2}&password={3}&smstype={4}&mobile={5}&content={6}", "MS", 0, "geovindu", sb.ToString(), 0, mobile, msg);//
            byte[] bytes = Encoding.GetEncoding("gbk").GetBytes(content);
            request.ContentLength = bytes.Length;
            Stream os = request.GetRequestStream();
            //req.GetResponseAsync();

            os.Write(bytes, 0, bytes.Length);
            os.Close();
            //System.Net.WebResponse resp = req.GetResponse();
            WebResponse resp = request.GetResponse();
            
            Task<WebResponse> task = Task.Factory.FromAsync(
                request.BeginGetResponse,
                asyncResult => request.EndGetResponse(asyncResult),
                (object)null);

            return task.ContinueWith(t => ReadStreamFromResponse(resp, content));
        }

        /// <summary>
        /// 对内容进行编码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static string UrlEncode(string str)
        {
            StringBuilder sb = new StringBuilder();
            byte[] byStr = System.Text.Encoding.GetEncoding("gbk").GetBytes(str); //默认是System.Text.Encoding.Default.GetBytes(str)
            for (int i = 0; i < byStr.Length; i++)
            {
                sb.Append(@"%" + Convert.ToString(byStr[i], 16));
            }

            return (sb.ToString());
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        private static string ReadStreamFromResponse(WebResponse response, string content)
        {
            Stream responseStream = response.GetResponseStream();
            using (StreamReader sr = new StreamReader(responseStream))
            {
                string strContent = sr.ReadToEnd();
                return strContent;
            }
        }



        delegate string SynchOperation(string value);
        /// <summary>
        /// 
        /// </summary>
        /// <param name="callback"></param>
        /// <param name="value"></param>
         void BeginTheSynchronousOperation(AsyncCallback callback, string value)
        {
            SynchOperation op = new SynchOperation(SynchronousOperation);
            op.BeginInvoke(value, callback, op);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
         string SynchronousOperation(string value)
        {

            string str = "geovindu";
            Thread.Sleep(10000);
            str = str + value;
            return str;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="result"></param>
         void CallbackOperation(IAsyncResult result)
        {
            // get your delegate
            var ar = result.AsyncState as SynchOperation;
            // end invoke and get value
            var returned = ar.EndInvoke(result);
            Response.Write(returned);
            
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button1_Click(object sender, EventArgs e)
        {
           BeginTheSynchronousOperation(CallbackOperation, this.TextBox1.Text.Trim());
            var task = MakeAsyncRequest("application/x-www-form-urlencoded", "geovindu", "1388888888");
            Response.Write(string.Format("Got response of {0}", task.Result));  //返回成功
        }

  第二种方法:  用HttpClient 更省代码  .net 4.6

 /// <summary>
    /// 发送
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button1_Click(object sender, EventArgs e)
    {

        Response.Write(isFail(sendMessage("138888888", "【六福珠宝】兴高高兴,天下为公", "geovindu")));

    }

    /// <summary>
    /// 发送信息
    /// geovindu 涂聚文
    /// </summary>
    /// <param name="mobile"></param>
    /// <param name="contenttxt"></param>
    /// <param name="user"></param>
    /// <returns></returns>
    private string sendMessage(string mobile, string contenttxt, string user)
    {
        string result = string.Empty;

        Uri u = new Uri("http://www.dusystem.com/smsSend.do");
        string pwd = "geovindu";// 
        string msg = UrlEncodeNew(contenttxt);
        var payload = string.Format("username={0}&password={1}&mobile={2}&content={3}", "geovindu", pwd, mobile, msg);
        HttpContent c = new StringContent(payload, Encoding.UTF8, "application/x-www-form-urlencoded");
        var t = Task.Run(() => PostURI(u, c));
        t.Wait();
        result=t.Result;
        return result;
    }
    /// <summary>
    /// 涂聚文 Geovin Du
    ///
    /// </summary>
    /// <param name="u"></param>
    /// <param name="c"></param>
    /// <returns></returns>
    static async Task<string> PostURI(Uri u, HttpContent c)
    {
        var response = string.Empty;
        using (var client = new HttpClient())
        {
            //string url = "http://myserver/method";
            //string content = "param1=1&param2=2";
            //HttpClientHandler handler = new HttpClientHandler();
            //HttpClient httpClient = new HttpClient(handler);
            //HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, u);
            //HttpResponseMessage response = await httpClient.SendAsync(request, content);

            HttpResponseMessage result = await client.PostAsync(u, c);
            if (result.IsSuccessStatusCode)
            {
                response = result.StatusCode.ToString();
                Task<string> t = result.Content.ReadAsStringAsync();
                response = t.Result;
            }
        }
        return response;
    }


    private bool isFail(string i)
    {
        bool ok = false;
        if (double.Parse(i) > 0)
        {
            ok = true;
        }
        return ok;
    }

  

 

转载于:https://www.cnblogs.com/geovindu/p/11287528.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值