本文主要.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; }
相關文檔:
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請求數據操作
推薦文檔
- Java EasyExcel讀取Excel表頭數據的方法及示例代碼
- Python pandas 遍歷DataFrame中的行數據的方法及示例代碼
- .NET(C#)使用HttpClient請求JSON數據的示例代碼
- Java JSoup 請求Url地址及處理響應的JSON數據方法代碼
- ASP.NET Core 使用HttpClient PostAsync POST Json數據
- Java EasyExcel讀取多行頭(Header)數據方法及示例代碼
- .NET Core(C#)使用WebView2 執行GET和POST請求的方法
- .NET Core(C#)方法返回多個的值方法及示例代碼