Post方式提交数据
string postUrl = "{\"PrintLog\":\"\",\"ModelName\":\"" + itemEntiy.ModelCode + "\",\"ProcessName\":\"" + itemEntiy.ProcessCode + "\"}";
using (HttpClient httpClient = new HttpClient())
{
//multipart/form-data方式
var content = new MultipartFormDataContent(DateTime.Now.Ticks.ToString("X"));
content.Add(new StringContent(postUrl), "queryJson");
var result = await httpClient.PostAsync("http://xxxx/CollectVariable?DataType=CollectVariableData", content);
string responseString = result.Content.ReadAsStringAsync().Result;
if (logger != null)
logger.LogInformation("Response status:{0}", result.StatusCode);
}
第2中方式:JSON参数写入body applition/json
using (HttpClient httpClient = sender.HttpClientFactory.CreateClient())
{
//var content = new MultipartFormDataContent(DateTime.Now.Ticks.ToString("X"));
//content.Add(new StringContent(postJson));
var buffer = Encoding.UTF8.GetBytes(postJson);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var requestMsg = await httpClient.PostAsync(auditurl, byteContent);
string auditjson = await requestMsg.Content.ReadAsStringAsync();
}
第三中方式:参数写入form application/x-www-form-urlencoded
则使用FormUrlEncodedContent
Get方式提交数据
using (HttpClient httpClient = new HttpClient())
{
var result = await httpClient.GetAsync("http://xxxx/CollectVariable?DataType=CollectVariableData?...");
string responseString = result.Content.ReadAsStringAsync().Result;
if (logger != null)
logger.LogInformation("Response status:{0}", result.StatusCode);
}
本文介绍了三种HTTP请求数据提交的方式:1) 使用POST方式附带URL字符串;2) 将JSON数据写入请求体,设置Content-Type为'application/json';3) 以form方式提交数据,Content-Type为'application/x-www-form-urlencoded'。示例代码展示了如何使用HttpClient在C#中实现这些方法。
902

被折叠的 条评论
为什么被折叠?



