【发布时间】:2019-10-21 17:13:16
【问题描述】:
我正在尝试向我的服务器发布一个联系人。 这就是我过去一直这样做的方式,直到我不得不使用字符串以外的对象。
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; }
}
【问题讨论】:
-
您是否正在尝试向 Match 类添加一个复杂的对象,并且想知道该怎么做?
-
我想知道如何处理请求,因为 FormUrlEncodedContent 只接受字符串/字符串
-
转到 quicktype.io 并将您的 JSON 粘贴到那里,让它为您生成一些 C# 存根
-
你可以使用
using (var postContent = new FormUrlEncodedContent(postParams.ToDictionary()))——但从不实际使用postContent。这是为什么呢?
标签: c# json http encoding httpclient