Csharp:HttpWebRequest , HttpClient and RestSharp
/// <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¶m2=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://github.com/restsharp/RestSharp //https://coronavirus-tracker-api.herokuapp.com/all Geovin Du var request = new RestRequest("/all", Method.GET); var client = new RestClient("https://coronavirus-tracker-api.herokuapp.com"); var response = client.ExecuteTaskAsync(request).Result; if (response.StatusCode != HttpStatusCode.OK) throw new Exception($"Unable to download file"); response.RawBytes.SaveAs(filename);
HttpWebRequest for control
WebClient for simplicity and brevity
RestSharp for both on non-.NET 4.5 environments
HttpClient for both + async features on .NET 4.5 environments
哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)