首页 > 解决方案 > 这个 WebClient 和 HttpClient 实现有什么不同?

问题描述

我想创建HttpClient这个 API 的更现代的实现:http: //api.txtlocal.com/docs/sendsms

我使用以下示例代码测试了他们的示例WebClientPOST 实现SendMessage2和新HttpClient实现SendMessageAsync

var sms = new TxtLocal(AuthenticationDetails.TxtLocalAPIKey, "Mister Boy","123456789");
var ret1 = sms.SendMessageAsync("Hello !").Result; //ugly hack for testing only
var ret2 = sms.SendMessage2("Hello!");

结果:

我看不出有什么不同,或者如何解决它,因为我没有收到任何错误。我已经PostAsJsonAsync成功地在其他类似的 WebHooks 上使用过。

using System;
using System.Collections.Specialized;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
using System.Web;

namespace Comms
{
    public class TxtLocal
    {
        static readonly string API_URL_BASE = "https://api.txtlocal.com/{0}/";
        static readonly string ENDPOINT_SEND = "send";

        private readonly string apiKey, sender, recipient;

        public TxtLocal(string apiKey,string sender,string recipient)
        {
            this.apiKey = apiKey;
            this.sender = sender;
            this.recipient = recipient;
        }
        public async Task<bool> SendMessageAsync(string message)
        {
            var response = await MakeCallAsync(ENDPOINT_SEND,new
            {
                apikey = apiKey,
                sender = sender,
                numbers = recipient,
                message = message
            });
            
            return response.IsSuccessStatusCode;
        }

        private async Task<HttpResponseMessage> MakeCallAsync(string method,object payload)
        {
            string endpoint = String.Format(API_URL_BASE, method);
            using (var client = new HttpClient())
            {
                return await client.PostAsJsonAsync(endpoint, payload);
            }
        }

        public bool SendMessage2(string message)
        {
            string endpoint = String.Format(API_URL_BASE, ENDPOINT_SEND);
            message = HttpUtility.UrlEncode(message);
            using (var wb = new WebClient())
            {
                byte[] response = wb.UploadValues(endpoint, new NameValueCollection()
                {
                {"apikey" , apiKey},
                {"numbers" , recipient},
                {"message" , message},
                {"sender" , sender}
                });
                string result = System.Text.Encoding.UTF8.GetString(response);
                return true;
            }
        }
    }
}

标签: webclientdotnet-httpclient.net-5

解决方案


推荐阅读