首页 > 解决方案 > 无法使用 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 )。

如果有人可以帮助我弄清楚如何组合一个用于使用HttpClientTrillian API 发出 POST 请求的工作方法,我将不胜感激。

ApiHelperHttpClient

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

标签: c#restapihttpclient

解决方案


推荐阅读