英文:
How to send form-data POST request with the help HttpClient with just Key-Value parameters
问题
如何使用HttpClient仅使用键值参数发送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 formData = new MultipartFormDataContent();
formData.Add(new StringContent(token), "__RequestVerificationToken");
formData.Add(new StringContent("admin"), "Username");
formData.Add(new StringContent("1"), "Password");
request.Content = formData;
HttpResponseMessage response = await Task.Run(() => client.SendAsync(request));
return response;
}
在JavaScript的Postan中相同的请求,它可以工作
英文:
How can I to send a form-data POST request with the help of HttpClient with just Key-Value parameters?
Here is my code of the method:
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;
}
答案1
得分: 2
这个问题是通过RestSharp解决的。我需要从该请求的响应中获取Set-Cookie头的值。我只是向RestClient添加了CookieContainer。不确定如何使用HttpClient解决此问题。谢谢所有尝试帮助的人。
英文:
This problem was resolved with the help of RestSharp. I needed to get Set-Cookie header value from the response of this request. And I just added CookieContainer to the RestClient. Not sure how to manage this problem with HttpClient.
Thanks everybody who was trying to help.
答案2
得分: 0
你没有正确等待。
尝试:var response = await client.SendAsync(request);
英文:
You are not awaiting correctly.
Try: var response = await client.SendAsync(request);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论