我正在尝试将一些JSON数据发布到API以添加帐户。 说明指定ids参数可以是:字符串(逗号分隔)或整数数组
我意识到我可以将逗号分隔的id放入查询字符串中但是我想将这些数据作为JSON发布,因为我可能有很多这些。
以下是我的尝试:
public static HttpClient GetHttpClient()
{
var property = Properties.Settings.Default;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(property.apiUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("X-OrgSync-API-Key", property.apiKey);
return client;
}
HttpClient client = Api.GetHttpClient();
string json = "{\"ids\":[10545801,10731939]}";
var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync($"{client.BaseAddress}/classifications/{classification.id}/accounts/add", httpContent);
它“成功”运行,但实际上没有在API服务器端设置。
关于我在这里做错了什么的任何想法? 此外,任何类型的工具/技术等,特别是在Visual Studio中,可以让我更好地了解请求/响应流量?
我知道这是可能的,因为当我使用像Postman这样的工具时它正确地添加了帐户ID:
答案 0 :(得分:1)
答案 1 :(得分:0)
尝试使用以下代码
using (var client= new HttpClient()) {
string json = "{\"ids\":[10545801,10731939]}";
var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync($"{client.BaseAddress}/classifications/{classification.id}/accounts/add", httpContent);
// If the response contains content we want to read it!
if (response .Content != null) {
var responseContent = await response.Content.ReadAsStringAsync();
//you will get your response in responseContent
}
答案 2 :(得分:0)
我能够通过将StringContent编码类型从Encoding.UTF8更改为null或Encoding.Default来获得json字符串方法。
string json = "{\"ids\":[10545801,10731939]}";
var httpContent = new StringContent(json, Encoding.Default, "application/json");
var response = await client.PostAsync($"{client.BaseAddress}/classifications/{classification.id}/accounts/add", httpContent);
我还想出了一种方法,可以使用包含int数组的id的对象和Encoding.UTF8;
HttpClient client = Api.GetHttpClient();
var postData = new PostData {ids = new[] {10545801,10731939}};
var json = JsonConvert.SerializeObject(postData);
var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync($"{client.BaseAddress}/classifications/{classification.id}/accounts/add", httpContent);
如果您不想仅仅为了存储帖子数据而创建一个类,您可以使用匿名类型:
var postData = new { ids = new[] {10545801,10731939}};
var json = JsonConvert.SerializeObject(postData);
var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync($"{client.BaseAddress}/classifications/{classification.id}/accounts/add", httpContent);