您好,我正在尝试使用 postman 发送带有 retrofit 的 POST 方法,到目前为止我可以说它正在工作,如果我使用 x-www-form-encoded 选项发送数据,我发送的 json 看起来像这样
{
"apt": "APT",
"apartment": "A103",
"author": "Someone",
"is_public": "True",
"is_complaint": "True",
"show_name": "True",
"title": "fhj",
"details": "vvkko"
}
我在 visual studio 中构建了我的类和我的模型以匹配它并将其粘贴到 json
namespace App.Models
{
public class ManyComplaints
{
public SingleComplaint data { get; set; }
}
public class SingleComplaint
{
public string apt { get; set; }
public string apartment { get; set; }
public string author { get; set; }
public string is_public { get; set; }
public string is_complaint { get; set; }
public string show_name { get; set; }
public string title { get; set; }
public string details { get; set; }
}
}
在这里我不确定我是否做对了这是我的 api 调用者
[Headers("Content-Type: application/x-www-form-urlencoded")]
[Post("/api/complaints/")]
Task SubmitComplaint([Body(BodySerializationMethod.UrlEncoded)]SingleComplaint complaint);
这是发送数据的代码
public async Task Post()
{
SingleComplaint data = new SingleComplaint
{
is_public = ShowPost,
is_complaint = Complaint,
show_name = ShowName,
author = Preferences.Get("UserName", null),
apt0 = Preferences.Get("Apt", null),
apartment = Preferences.Get("Apartment", null),
title = TitleEntry.Text,
details = DetailsEntry.Text
};
try
{
var myApi = RestService.For<IApiService>(Constants.webserver);
var serialized = JsonConvert.SerializeObject(data);
ManyComplaints complaint = await myApi.SubmitComplaint(data);
await DisplayAlert("Thanks", "Your message has been succesfully delivered", "Ok");
}
catch (Exception ex)
{
await Application.Current.MainPage.DisplayAlert("Error", ex.Message, "Ok");
}
}
尝试将该行用作 string complaint = await myApi.SubmitComplaint(serialized);
并将其更改为字符串而不是 ManyComplaints
类,
还尝试将模型更改为单一投诉,但我无法让它工作,我缺少什么或如何让它工作?
最佳答案
这个答案可能来得很晚。但最近我正在研究一个类似的用例。下面的代码对我有用。
API 声明(使用 Refit)
[Headers("Content-Type: application/x-www-form-urlencoded")]
[Get("")]
public HttpResponseMessage GetData([Body(BodySerializationMethod.UrlEncoded)] FormUrlEncodedContent content);
调用 API
List<KeyValuePair<string, string>> contentKey = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("apt", "APT"),
new KeyValuePair<string, string>("apartment", "A103"),
new KeyValuePair<string, string>("author", "Someone")
};
FormUrlEncodedContent content = new FormUrlEncodedContent(contentKey);
HttpResponseMessage response = someClass.GetData(content);
关于c# - 如何序列化我的类(class)以通过 retrofit 将其作为 urlencoded 发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57964166/