![](/img/trans.png)
[英]How to POST request in c# with content-type being x-www-form-urlencoded?
[英]C# HttpClient REST request using Content-Type: application/x-www-form-urlencoded
我正在嘗試調試此請求,但我看不出我做錯了什么。 該請求是針對身份驗證信息的,非常簡單。
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'
這是我最近的努力。
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();
}
我可以在調試器中看到 Content-Type header 已設置(client.Content.Headers)。 並且 Accept 也設置了(client.Headers)。
我不確定我是否正確設置了正文內容。 我有 62 個字符。 在請求中它說我有 63 組,但我無法弄清楚如何在請求中實際查看或打印正文內容......
打印語句給出了這個:
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
}
這是錯誤:
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
}
[編輯] 使用 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();
}
這會將表單主體轉義為如下內容:“user_name%3decommemail%26password%3abc123m%26auth_type%3dpassword”
我收到一個 400 Bad Request 錯誤,我認為這是一個進步。
嘗試使用 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.