首页 文章详情

.<em><!--red_beg-->NET<!--red_end--></em> Core(C#) POST JSON数据和Form表单的方法及示例代码

llovebo | 364 2021-09-25 07:29 0 0 0
UniSMS (合一短信)

本文主要.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;
}

出处:https://www.cjavapy.com/mip/684/


版权申明:本文来源于网友收集或网友提供,仅供学习交流之用,如果有侵权,请转告版主或者留言,本公众号立即删除。


支持小微:

腾讯云 搞活动了?玩服务器的可以搞搞。就这几天时间。

轻量  1C2G6M 60GB SSD盘297元/3年

链接:https://curl.qcloud.com/bR8ycXZa

右下角,您点一下在看图片520d7aad86084383f71363a61e6fd7fb.webp

小微工资涨1毛

商务合作QQ:185601686


69bc00313bb742d6ac40b8974dc76148.webp




good-icon 0
favorite-icon 0
收藏
回复数量: 0
    暂无评论~~
    Ctrl+Enter