簡體   English   中英

C# HttpClient 請求 API 套件

[英]C# HttpClient request API suite

我正在嘗試開發一個 API 套件,所以我可以通過傳遞一些參數來調用它。 我成功地制作了關於 GET 方法的部分。 POST 似乎有點復雜,我沒有找到任何來源,所以我可以理解如何制作它。 我的計划是使用正文作為參數調用 POST

這是我開發的 GET 請求,你能幫我理解如何使用 POST 方法來實現它嗎?:

static void Main(string[] args)
    {
        string url = ConfigurationManager.AppSettings["url"];
        string jsonBody = "";
        string method = "GET";
        string result = CallApi(url, method, jsonBody);
    }

    public static string CallApi(string url, string method, string bodyInput)
    {
        string bodyOutput = null;
        HttpClient client = new();
        Uri uri = new(url);

        switch (method)
        {
            case "GET":
                Task<HttpResponseMessage> response = client.GetAsync(uri);
                HttpResponseMessage result = response.Result;
                HttpContent content = result.Content;
                bodyOutput = content.ReadAsStringAsync().Result;
                break;

            case "POST":
                //bodyInput
                break;

            case "PUT":
                break;

            case "DELETE":
                break;

            default:
                break;
        }

        return bodyOutput;
    }
}

謝謝

您好,您的代碼應如下所示:

static async Task Main(string[] args)
    {
        string baseAddress = ConfigurationManager.AppSettings["baseAddress"];
        string path = ConfigurationManager.AppSettings["path"];

        string jsonBody = "";
        HttpMethod method = HttpMethod.Get;

        string result = await CallApi(baseAddress, path, method, jsonBody);
    }

    public static async Task<string> CallApi(string baseAddress, string path, HttpMethod method, string body)
    {
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri(baseAddress);

        HttpResponseMessage response = null;
        switch (method)
        {
            case HttpMethod.Get:
                response = await client.GetAsync(path);
                break;
            case HttpMethod.Post:
            response = await client.PostAsJsonAsync(path, body);
                break;
            case HttpMethod.Put:
                response = await client.PutAsJsonAsync(path, body);
                break;
            case HttpMethod.Delete:
                response = await client.DeleteAsync(path);
                break;
            default:
                throw new NotImplementedException();
        }

        // Throw an exception if the response code is not successful
        response.EnsureSuccessStatusCode();

        // Read the response
        string bodyOutput = await response.Content.ReadAsStringAsync();
        return bodyOutput;
    }
}

您可以在此處查看更詳細的示例: https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client

使用 await 調用此 function,這與您在 function 中所做的不同。 郵政:

static async Task Postfunc()
{
  
    var json = Newtonsoft.Json.JsonConvert.SerializeObject(new object obj());
    var data = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json");

    var client = new HttpClient();

    var response = await client.PostAsync(url, data);

    string result = response.Content.ReadAsStringAsync();
    Console.WriteLine(result);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM