[英]C# HttpClient REST request using Content-Type: application/x-www-form-urlencoded
I'm trying to debug this request, but I don't see what I'm doing wrong.我正在尝试调试此请求,但我看不出我做错了什么。 The request is for auth info, and it's pretty simple.该请求是针对身份验证信息的,非常简单。
curl -i -X POST \
-H "Content-Type:application/x-www-form-urlencoded" \
-d \
'user_name=ecommemail&password=abc123&auth_type=password' \
'https://sample.com/api/auth/token'
Here is my latest effort.这是我最近的努力。
authUrl = https://sample.com/api/auth/token;
private async Task<string> GenerateAccessObject2()
{
HttpClientHandler handler = new HttpClientHandler() { UseDefaultCredentials = false };
HttpClient client = new HttpClient(handler);
client.BaseAddress = new(authUrl);
//client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("username", "email"));
postData.Add(new KeyValuePair<string, string>("password", "abc123"));
postData.Add(new KeyValuePair<string, string>("auth_type", "password"));
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, authUrl) { Content = new FormUrlEncodedContent(postData) };
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
System.Console.WriteLine(request.ToString());
System.Console.WriteLine(request.Content);
HttpResponseMessage response = await client.SendAsync(request);
return response.ToString();
}
I can see in the debugger that the Content-Type header is set (client.Content.Headers).我可以在调试器中看到 Content-Type header 已设置(client.Content.Headers)。 And the Accept is set too (client.Headers).并且 Accept 也设置了(client.Headers)。
I'm not sure I'm setting the body content correctly though.我不确定我是否正确设置了正文内容。 I have 62 characters worth.我有 62 个字符。 In the request it says I have 63 set, but I can't figure out how to actually see or print the body content in the request...在请求中它说我有 63 组,但我无法弄清楚如何在请求中实际查看或打印正文内容......
The print statement gives this:打印语句给出了这个:
Method: POST, RequestUri: 'https://sample.com/api/auth/token', Version: 1.1, Content: System.Net.Http.FormUrlEncodedContent, Headers:
{
Content-Type: application/x-www-form-urlencoded
}
And here is the error:这是错误:
StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
Max-Forwards: 20
Via: 1.0 sample.com ()
Connection: close
X-CorrelationID: Id-d26af9610df7cc527996cde2 0
Date: Tue, 01 Feb 2022 17:16:02 GMT
Server: Apache
Transfer-Encoding: chunked
Content-Type: application/json
}
[EDIT] Another effort using MihalBy's idea. [编辑] 使用 MihalBy 的想法的另一项努力。
private async Task<string> GenerateAccessObject3()
{
HttpClientHandler handler = new HttpClientHandler() { UseDefaultCredentials = false };
HttpClient client = new HttpClient(handler);
client.BaseAddress = new(authUrl);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string postData = HttpUtility.UrlEncode(authBody, Encoding.GetEncoding(65001));
byte[] data = System.Text.Encoding.GetEncoding(65001).GetBytes(postData);
ByteArrayContent content = new ByteArrayContent(data);
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
HttpResponseMessage response = await client.PostAsync(authUrl, content);
return response.ToString();
}
This escapes the form body into something like this: "user_name%3decommemail%26password%3abc123m%26auth_type%3dpassword"这会将表单主体转义为如下内容:“user_name%3decommemail%26password%3abc123m%26auth_type%3dpassword”
And I get a 400 Bad Request error, which I consider progress.我收到一个 400 Bad Request 错误,我认为这是一个进步。
try to post using FormUrlEncodedContent尝试使用 FormUrlEncodedContent 发布
HttpClientHandler handler = new HttpClientHandler() { UseDefaultCredentials = false };
HttpClient client = new HttpClient(handler);
client.BaseAddress = new(authUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var data=new Dictionary<string, string>()
{
{"username", "email"},
{"password", "abc123"}
{ "auth_type", "password"}
};
var content = new FormUrlEncodedContent(data);
var response = await client.PostAsync(authUrl, content);
if (response.IsSuccessStatusCode)
{
var stringData = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<object>(stringData);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.