这个 WebClient 和 HttpClient 实现有什么不同?

问题描述

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

我使用以下示例代码测试了他们的示例 WebClient POST 实现 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!");

结果:

  • SendMessage2 使 API 触发并发送 SMS 消息
  • SendMessageAsync 收到 HTTP OK,但没有发送任何消息。

我看不出有什么不同,也看不到如何修复它,因为我没有收到错误回复。我已经成功地在其他类似的 WebHook 上使用了 PostAsJsonAsync

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;
            }
        }
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)