gpt4 book ai didi

C# HttpClient 在字典字符串/对象中使用 FormUrlEncodedContent 对象发布内容

转载 作者:行者123 更新时间:2023-12-05 02:10:40 24 4
gpt4 key购买 nike

我正在尝试向我的服务器发布一个联系方式。这就是我过去一直这样做的方式,它一直有效,直到我不得不使用字符串以外的对象。

using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(authType, tokens);
var postParams = new Dictionary<string, object>();

postParams.Add("string", string);
postParams.Add("int", string);
postParams.Add("datetime", DateTime);
postParams.Add("datetime", DateTime);
postParams.Add("Match", Match);
postParams.Add("TicketId", token);

using (var postContent = new FormUrlEncodedContent(postParams.ToDictionary()))
{
var myContent = JsonConvert.SerializeObject(postParams);
var buffer = System.Text.Encoding.UTF8.GetBytes(myContent);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

using (HttpResponseMessage response = await client.PostAsync(@"http://url/api", byteContent))
{
response.EnsureSuccessStatusCode(); // Throw if httpcode is an error
using (HttpContent content = response.Content)
{
string result = await content.ReadAsStringAsync();
var Json = JsonConvert.DeserializeObject<bool>(result);
return Json;
}
}
}
}

这就是我的请求应该是这样的。

methode: POST
object: {
"title":"test-ticket-2",
"detail": "Description test create ticket in prod",
"dateStart": "2019-10-06",
"dateEnd": "2019-10-12",
"ratio": "2.15",
"matchResult": "2",
"matchs": [
{
"Teams": "Test-match-1",
"Proposal": "3x",
"DateStart": "2019-10-06 18:00",
"DateEnd": "2019-10-06 20:00",
"Payout": "0.6"
}
]

我不知道是否以及如何添加字符串以外的对象并发出请求。有什么想法吗?

编辑:Match 看起来像这样

public class Match
{
public int Id { get; set; }
public string Teams { get; set; }
public string MatchResults { get; set; }
public string Proposal { get; set; }
public string Payout { get; set; }
public DateTime? DateStart { get; set; }
public DateTime? DateEnd { get; set; }
public Uri Ball { get; set; }
public int TicketId { get; set; }
}

最佳答案

HOW I can add Objects other than string and make the request. Any ideas?

using (HttpClient httpclient = new HttpClient()) 
{
Models.ApplicationUser applicationUser = new ApplicationUser();
string serialized = Newtonsoft.Json.JsonConvert.SerializeObject(applicationUser);
StringContent stringContent = new StringContent(serialized);
httpclient.PostAsync("url", stringContent);
}

希望你想做这样的事情

关于C# HttpClient 在字典字符串/对象中使用 FormUrlEncodedContent 对象发布内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58491164/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com