【问题标题】:How to send form-data POST request with the help HttpClient with just Key-Value parameters如何仅使用键值参数在 HttpClient 的帮助下发送表单数据 POST 请求
【发布时间】:2020-01-06 17:02:26
【问题描述】:

如何在 HttpClient 的帮助下仅使用 Key-Value 参数发送 form-data POST 请求?

这是我的方法代码:

public async Task<HttpResponseMessage> MakePostAsync(string endpoint, string token, Dictionary<string, string> headers = null, KeyValuePair<string, string>[] parameters = null)
        {
            var request = new HttpRequestMessage(HttpMethod.Post, endpoint);
            if (headers != null)
            {
                foreach (var header in headers)
                    request.Headers.Add(header.Key, header.Value);
            }
            request.Headers.Add("Content-Type", "multipart/form-data");
            var formaData = new MultipartFormDataContent();

            formaData.Add(new StringContent(token), "__RequestVerificationToken");
            formaData.Add(new StringContent("admin"), "Username");
            formaData.Add(new StringContent("1"), "Password");
            request.Content = formaData;


            HttpResponseMessage response = await Task.Run(() => client.SendAsync(request));
            return response;
        }

The same request in the Postan on JavaScript, but it works

【问题讨论】:

  • 你得到什么响应信息?
  • 为什么 "HttpResponseMessage response = await Task.Run(() => client.SendAsync(request));" 而不是 "HttpResponseMessage response = await client. SendAsync(request);" ?
  • 并且,你确定你在邮递员中使用 multipart/form-data 发送吗?看起来邮递员正在发送文本/json?
  • so.. 有一个 Content-Type 的请求“multipart/form-data;boundary=---------------------- ----939589509105609250428586"
  • @Andrew - 你在使用邮递员时看到了吗?

标签: c# request multipartform-data dotnet-httpclient


【解决方案1】:

这个问题在 RestSharp 的帮助下得到了解决。我需要从这个请求的响应中获取 Set-Cookie 标头值。我刚刚将 CookieContainer 添加到 RestClient。不确定如何使用 HttpClient 管理此问题。 感谢所有试图提供帮助的人。

【讨论】:

  • 类似这样的东西: System.Net.CookieContainer usercookie = new CookieContainer(); var httpClient = new System.Net.Http.HttpClient(new System.Net.Http.HttpClientHandler { CookieContainer = usercookie });
【解决方案2】:

你没有正确地等待。

试试:var response = await client.SendAsync(request);

【讨论】:

  • 你能安装一个像fiddler这样的工具并捕获出去的http请求吗?
猜你喜欢
  • 2021-07-27
  • 2015-10-20
  • 1970-01-01
  • 2020-01-04
  • 2020-06-05
  • 1970-01-01
  • 1970-01-01
  • 2011-10-03
相关资源
最近更新 更多