webclient - 这个 WebClient 和 HttpClient 实现有什么不同?
问题描述
我想创建HttpClient
这个 API 的更现代的实现: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 但未发送任何消息。
我看不出有什么不同,或者如何解决它,因为我没有收到任何错误。我已经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;
}
}
}
}
解决方案
推荐阅读
- caching - web.config 缓存设置不起作用
- export - 将部分页面渲染到文件
- node.js - 多容器 Docker 应用程序部署失败
- python - python 正则表达式读取部分文本文件
- javascript - Firefox 停止调用 AJAX 函数
- python - 根据列标题添加新行
- f# - Xamarin Android:资源未拾取 F# 图标
- r - dimnames(s$v) <- list(colnames(x), paste0("PC", j)) 中的错误:dimnames 2 的错误长度不等于数组范围
- asp.net-core - asp.net核心部署持久错误代码='0x80004005:8000808c。在赢 2012r2
- azure - 逻辑应用性能是否取决于连接器?