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

标签 c# httpclient rest

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/

相关文章:

c# - WPF - C# - 仅打开父窗口一次

c# - 如何使用 FileOpenDialog 在 C# 中打开文件

java - DefaultHttpClient 超时

c# - 无法创建任务 <HttpResponseMessage> "await"

rest - 如何在 win 上查看 httpS 请求和 header ?

java - Spring MVC 请求映射 - 完整请求 URI

c# - 为什么 View 设置为 Details 的 C# ListView 控件仍然为空?

c# - 当值为空时,Razor html 标签不会获取 ID

java - Android响应脚本问题

java - 使用 xml 配置 Jersey RESTFUL