繁体   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