HttpClient 使用(一)Get、Post 请求

  最近发现不少新人不知道怎么在后台发起Http请求,简单分享一下,HttpClient 因为是自带的,所以选择分享这个,还有不少优秀的库,例如 Flurl,或者 Refit。

  而说到 Get、Post,就不得不提一下 rest 了,具体是什么呢,感兴趣的可以移步看文档,我不多叙述:传送门

按照惯例,废话不多说,代码走起

GET

using var client = httpClientFactory.CreateClient();
var url = "https://localhost:7237/api/methods/GET/Route/UploaFile?method=GET&value=Query";
var resp = await client.GetAsync(url);

var str = await resp.Content.ReadAsStringAsync();

 

POST

包含文件与表单

var content = new MultipartFormDataContent
{
    { new StringContent("POST", Encoding.UTF8), "Method" },
    { new StringContent("Form", Encoding.UTF8), "Value" },
    { new StringContent(JsonSerializer.Serialize(new Parameter(){ Method = "POST",Value = "Body"}),Encoding.UTF8, "application/json") },
    { new ByteArrayContent(System.IO.File.ReadAllBytes(@"C:\Users\ysmc_\Downloads\file.txt")), "files", "file.txt" }
};

using var client = httpClientFactory.CreateClient();
var url = "https://localhost:7237/api/methods/GET/Route/UploaFile?method=GET&value=Query";
var resp = await client.PostAsync(url, content);

var str = await resp.Content.ReadAsStringAsync();

API

[HttpPost("{method}/{value}/UploaFile")]
public async Task<Dictionary<string, object>> UploadFileAsync(
    [FromRoute] Parameter route,
    [FromQuery] Parameter query,
    [FromForm] Parameter form,
    IEnumerable<IFormFile> files)
{
    var fileStream = files.FirstOrDefault()?.OpenReadStream();
    var fileContent = new StringBuilder();
    if (fileStream != null)
    {
        using var reader = new StreamReader(fileStream!);
        while (reader.Peek() >= 0)
        {
            fileContent.AppendLine(await reader.ReadLineAsync());
        }
    }

    var result = new Dictionary<string, object>()
    {
        ["route"] = route,
        ["query"] = query,
        ["form"] = form,
        ["fileContent"] = fileContent.ToString()
    };

    return result;
}

 

posted @ 2024-03-20 22:35  一事冇诚  阅读(140)  评论(2编辑  收藏  举报