c# - 无法使用 HttpClient 向 RESTful API 发出 post 请求
问题描述
我一直在尝试使用 Trillian API https://trillian.im/help/api/v2/#send-a-message-to-a-group-chat发出 POST 请求以发送群聊消息
它可以使用 发出 POST 请求HttpWebRequest
,为此我已经包含了工作代码。我想要的是能够使用HttpClient
.
我似乎无法组合一种用于HttpClient
制作该 POST 的方法。我最终得到了 401 错误,这意味着 API 令牌无效,但它绝对有效,因为它适用于HttpWebRequest
.
需要注意的一件事是,我有一个ApiHelper
正在使用的附加类,HttpClient
以便我可以HttpClient
在应用程序中重用一个(Tim Corey 的想法:https ://youtu.be/aWePkE2ReGw?t=367 )。
如果有人可以帮助我弄清楚如何组合一个用于使用HttpClient
Trillian API 发出 POST 请求的工作方法,我将不胜感激。
ApiHelper
类HttpClient
:
public static class ApiHelper
{
public static HttpClient ApiClient { get; set; }
public static void InitializeClient()
{
ApiClient = new HttpClient();
ApiClient.DefaultRequestHeaders.Accept.Clear();
ApiClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
}
}
破碎的代码使用HttpClient
public static void HttpClientPOST()
{
//%23 is an encoded #
string groupID = "%23groupChatIDHere";
string url = "https://impp.name.net/v2/name.net/groupchats/" + groupID + "/messages/";
string fromParam = "trillian@name.net";
string messageParam = "test message";
string urlTokenParam = "tokenCodeHere";
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("from", fromParam);
parameters.Add("message", messageParam);
parameters.Add("token", urlTokenParam);
var content = new FormUrlEncodedContent(parameters);
ApiHelper.ApiClient.BaseAddress = new Uri(url);
var task = Task.Run(() => ApiHelper.ApiClient.PostAsync(ApiHelper.ApiClient.BaseAddress, content));
task.Wait();
var response = task.Result;
if (response.IsSuccessStatusCode)
{
var success = response.IsSuccessStatusCode;
}
else
{
throw new Exception(response.ReasonPhrase);
}
}
工作代码使用HttpWebRequest
public static int HttpWebRequestPOST()
{
//%23 is an encoded #
string groupID = "%23groupChatIDHere";
string Url = "https://impp.name.net/v2/name.net/groupchats/" + groupID + "/messages/";
//Start the creation of the web API request as a POST method
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
string fromParam = "from=trillian%40name.net";
string messageParam = "&message=test message";
string urlTokenParam = "&token=tokenCodeHere";
//Encode the information to be able to send the call to API
Byte[] byteArray = encoding.GetBytes(fromParam + messageParam + urlTokenParam);
//Set the content type to allow paramaters to be passed via URL
request.ContentLength = byteArray.Length;
request.ContentType = @"application/x-www-form-urlencoded";
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
long length = 0;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
length = response.ContentLength;
return Convert.ToInt32(response.StatusCode);
}
}
catch (WebException ex)
{
HttpWebResponse errorResponse = (HttpWebResponse)ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
return Convert.ToInt32(errorResponse.StatusCode);
}
}
}
解决方案
推荐阅读
- java - 读取文件 - 哪种方法是可测试的?
- javascript - 证明工作量证明是在特定机器上计算的?
- spring-boot - HttpClientErrorException$BadRequest: 400 : [no body] 调用 restTemplate.postForObject 时
- visual-studio - 脚本需要从 MonoBehavior 派生
- javascript - d3.js 是否有 drop 事件?
- performance - 使用游标 PLSQL 的性能
- alpacajs - 使用 Json 对象更新时,Alpaca setValue 不替换值
- php - 使用贝宝实现产品购买的简单方法
- react-native - 如何在 android 上像 IOS 一样在 react native 中获得相同大小的滑块拇指
- javascript - 使用数组方法从数组中获取最受欢迎的值