.NET Core(C#) POST JSON数据和Form表单的方法及示例代码

本文主要.NET Core(C#)中,通过后台代码提交JSON格式,提交Form(application/x-www-form-urlencoded或multipart/form-data)表单数据请求的方法,以及相关的示例代码。

1、POST提交JSON格式数据

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = "{\"user\":\"test\"," +
                  "\"password\":\"bla\"}";
    streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

相关文档.Net(C#)后台发送Get和Post请求的几种方法总结

2、POST提交Form表单数据

1) type为"application/x-www-form-urlencoded"类型的表单

/// <summary>
/// 执行POST请求
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
/// <param name="headers">填充消息头</param>        
/// <returns></returns>
public static string HttpPost(string url, string paramData, Dictionary<string, string> headers = null, string contentType = "application/json", int timeOut = 30)
{
    using (HttpClient client = new HttpClient())
    {
        if (headers != null)
        {
            foreach (var header in headers)
                client.DefaultRequestHeaders.Add(header.Key, header.Value);
        }
        using (HttpContent httpContent = new StringContent(paramData, Encoding.UTF8))
        {
            if (contentType != null)
                httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
            HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
            return response.Content.ReadAsStringAsync().Result;
        }
    }
}

2) type为"multipart/form-data"类型的表单

public async Task<string> UploadFile(string filePath)
{
    if (string.IsNullOrWhiteSpace(filePath))
    {
        throw new ArgumentNullException(nameof(filePath));
    }
    if (!File.Exists(filePath))
    {
        throw new FileNotFoundException($"File [{filePath}] not found.");
    }
    using var form = new MultipartFormDataContent();
    using var fileContent = new ByteArrayContent(await File.ReadAllBytesAsync(filePath));
    fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
    form.Add(fileContent, "file", Path.GetFileName(filePath));
    //表单中其它参数
    form.Add(new StringContent("789"), "userId");
    form.Add(new StringContent("some comments"), "comment");
    form.Add(new StringContent("true"), "isPrimary");
    var response = await _httpClient.PostAsync($"{_url}/api/files", form);
    response.EnsureSuccessStatusCode();
    var responseContent = await response.Content.ReadAsStringAsync();
    var result = JsonSerializer.Deserialize<FileUploadResult>(responseContent);
    _logger.LogInformation("Uploading is complete.");
    return result.Guid;
}

相关文档:

.Net(C#)后台发送Get和Post请求的几种方法总结

ASP.net Core 通过模型绑定接收get和post请求参数

.net Core(C#) RestSharp get和post请求、下载大文件及cookie管理

.net(C#) Fluent HTTP (Flurl get和post请求)使用方法及示例代码

.net(C#) 后台使用WebClient(客户端控制台程序)执行get和post请求的方法

.net Core 使用HttpClient通过配置Proxy(代理)执行get和post请求数据操作

推荐阅读
cjavapy编程之路首页