Csharp:HttpWebRequest , HttpClient and RestSharp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/// <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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/// <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;
   }

  

 

1
2
3
4
5
6
7
8
//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

 

posted @   ®Geovin Du Dream Park™  阅读(693)  评论(2编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
历史上的今天:
2017-08-02 csharp: FTP Client Library using System.Net.FtpWebRequest
2017-08-02 csharp: FTP Client Library using System.Net.FtpClient and FluentFTP,测试中存在的BUG修正
2016-08-02 csharp: Export DataTable to Excel using OpenXml 2.5 in asp.net
2016-08-02 csharp:asp.net Importing or Exporting Data from Worksheets using aspose cell
2012-08-02 csharp Remove Empty rows in datatable
2012-08-02 csharp read excel file get sheetName list
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示