這就是POST請求,它是有效的。
這就是POST請求,它是有效的。
curl -X POST --header 'Accept: application/json'
'http://mywebsite.com/api/CompleteService?refId=12345&productPrice=600'。
如何使用C# => HttpClient => client.PostAsync()方法發送這個請求?
已經嘗試了兩種方法,但都失敗了。
方法1(失敗,回應404)
string url = "http://mywebsite.com/api/CompleteService"/span>;
string refId = "12345";
string price= "600";
string param = $"refId ={refId}& productPrice ={price}"。
HttpContent content = new StringContent(param, Encoding.UTF8, "application/json") 。
HttpResponseMessage response = client.PostAsync(url, content).Result;
這只有在API接受請求體而不是查詢字串的情況下才會起作用。
方法 2 (Failed, Response 404) https://stackoverflow.com/a/37443799/7768490
var parameters = new Dictionary< string, string> { { "refId", refId }, { "productPrice", price} };
var encodedContent = new FormUrlEncodedContent(引數)。
HttpResponseMessage response = client.PostAsync(url, encodedContent)
uj5u.com熱心網友回復:
顯然,所有嘗試過的方法都沒有在URL中放置引數!。你是在下面的URL上發布的
"http://mywebsite.com/api/CompleteService"/span>
然而,有些東西是可行的
string url = "http://mywebsite.com/api/CompleteService?"。
string refId = "12345";
string price= "600";
string param = $"refId={refId}& productPrice={price}"/span>。
HttpContent content = new StringContent(param, Encoding.UTF8, "application/json") 。
將引數附加到URL,并獲得回應的主體,使用:
將引數附加到URL,并獲得回應的主體。
try
{
HttpResponseMessage response = await client.PostAsync(url param, content)。
response.EnsureSuccessStatusCode()。
string responseBody = await response.Content.ReadAsStringAsync()。
Console.WriteLine(responseBody)。
}
catch(HttpRequestException e)
{
Console.WriteLine("Message :{0}",e.Message) 。
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/331334.html
標籤:
