gpt4 book ai didi

c# - 在 C# HttpClient 中发送表单数据

转载 作者:行者123 更新时间:2023-12-02 18:42:18 26 4
gpt4 key购买 nike

enter image description here您好,我正在使用 C# HttpClient 从 api 中提取数据。我需要使用 post 方法以表单数据形式提取数据。我写了下面的代码,但得到了一个空的回应。我该怎么做?

var client = new HttpClient();

client.Timeout = TimeSpan.FromSeconds(300);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));

var request = new HttpRequestMessage();
request.Method = HttpMethod.Post;
request.RequestUri = new Uri("https://myapi.com");

var content = new MultipartFormDataContent();

var dataContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("value1", "myvalue1"),
new KeyValuePair<string, string>("value2", "myvalue2"),
new KeyValuePair<string, string>("value3", "myvalue3")
});
content.Add(dataContent);

request.Content = content;
var header = new ContentDispositionHeaderValue("form-data");
request.Content.Headers.ContentDisposition = header;

var response = await client.PostAsync(request.RequestUri.ToString(), request.Content);
var result = response.Content.ReadAsStringAsync().Result;

最佳答案

您使用 FormUrlEncodedContent 以错误的方式发送数据。

要将参数作为 MultipartFormDataContent 字符串值发送,您需要替换以下代码:

var dataContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("key1", "myvalue1"),
new KeyValuePair<string, string>("key2", "myvalue2"),
new KeyValuePair<string, string>("key3", "myvalue3")
});

有了这个:

content.Add(new StringContent("myvalue1"), "key1");
content.Add(new StringContent("myvalue2"), "key2");
content.Add(new StringContent("myvalue3"), "key3");

关于c# - 在 C# HttpClient 中发送表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67848923/

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