C#:HttpClient POST传递参数 - 一个字符串和一个int数组

时间:2016-09-17 21:18:56

标签: c# post httpclient

我在调用API方面遇到了一些问题。我需要发送包含两件事的帖子数据:一个ID和一个int数组。 我尝试了很多东西,都导致错误或者只是没有以正确的方式发送数据。我找到的所有答案都没有处理我想发送2种不同数据类型的事实。

另一方面,我有:

dynamic apiVar = new ExpandoObject();
var propertyName = "Name";
apiVar[propertyName] = "Test";
propertyName = "Start";
apiVar[propertyName] = 1;
propertyName = "Stop";
apiVar[propertyName] = 2;

我试过了:

Call<DefaultResponseList> someMethod(@Field("parm1") String parm1, @Field("parm2[]") ArrayList<Integer> parm2);

2 个答案:

答案 0 :(得分:3)

我解决了这个问题。 感谢Cihan Uygun的评论。

List<int> ids = new List<int>();
ids.Add(1);
ids.Add(2);
ids.Add(3);

var values = new List<KeyValuePair<string, string>>
{
    new KeyValuePair<string, string>("parm1", "lkdjfowejfd123")
};

int counter = 0;
foreach (int i in ids)
{
    values.Add(new KeyValuePair<string, string>("parm2[" + counter.ToString() + "]", i.ToString()));
    counter++;
}

var httpClient = new HttpClient(new HttpClientHandler());
HttpResponseMessage response = await httpClient.PostAsync(urlSaveRegions, new FormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();

string data = await response.Content.ReadAsStringAsync();

答案 1 :(得分:0)

使用StringContext发布整数数组

var myData = new { myvar = "my string", data = new[] {1,2,3,4,5}};

var httpClient = new HttpClient(new HttpClientHandler());

var jsonObject = JsonConvert.SerializeObject(myData)
var stringContent = new StringContent(jsonObject.ToString(), System.Text.Encoding.UTF8, "application/json");

HttpResponseMessage response = await httpClient.PostAsync(urlSaveRegions, stringContent);
response.EnsureSuccessStatusCode();

string data = await response.Content.ReadAsStringAsync();