我已经编写了以下代码来发送标题,发布参数。问题是我使用SendAsync,因为我的请求可以是GET或POST。如何将POST Body添加到此代码中,以便如果有任何帖子正文数据,则会在我发出的请求中添加它,如果它的简单GET或POST没有正文,则会以此方式发送请求。请更新以下代码:
HttpClient client = new HttpClient();
// Add a new Request Message
HttpRequestMessage requestMessage = new HttpRequestMessage(RequestHTTPMethod, ToString());
// Add our custom headers
if (RequestHeader != null)
{
foreach (var item in RequestHeader)
{
requestMessage.Headers.Add(item.Key, item.Value);
}
}
// Add request body
// Send the request to the server
HttpResponseMessage response = await client.SendAsync(requestMessage);
// Get the response
responseString = await response.Content.ReadAsStringAsync();
答案 0 :(得分:85)
这取决于您拥有的内容。您需要使用新的HttpContent初始化requestMessage.Content
媒体资源。例如:
...
// Add request body
if (isPostRequest)
{
requestMessage.Content = new ByteArrayContent(content);
}
...
其中content
是您的编码内容。您还应该包含正确的内容类型标题。
哦,它可以更好(从answer开始):
requestMessage.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}", Encoding.UTF8, "application/json");
答案 1 :(得分:5)
我是按照以下方式实现的。我想要一个通用的MakeRequest
方法,可以调用我的API并接收请求正文的内容 - 并将响应反序列化为所需的类型。我创建了一个Dictionary<string, string>
对象来容纳要提交的内容,然后用它设置HttpRequestMessage
Content
属性:
调用API的通用方法:
private static T MakeRequest<T>(string httpMethod, string route, Dictionary<string, string> postParams = null)
{
using (var client = new HttpClient())
{
HttpRequestMessage requestMessage = new HttpRequestMessage(new HttpMethod(httpMethod), $"{_apiBaseUri}/{route}");
if (postParams != null)
requestMessage.Content = new FormUrlEncodedContent(postParams); // This is where your content gets added to the request body
HttpResponseMessage response = client.SendAsync(requestMessage).Result;
string apiResponse = response.Content.ReadAsStringAsync().Result;
try
{
// Attempt to deserialise the reponse to the desired type, otherwise throw an expetion with the response from the api.
if (apiResponse != "")
return JsonConvert.DeserializeObject<T>(apiResponse);
else
throw new Exception();
}
catch (Exception ex)
{
throw new Exception($"An error ocurred while calling the API. It responded with the following message: {response.StatusCode} {response.ReasonPhrase}");
}
}
}
调用方法:
public static CardInformation ValidateCard(string cardNumber, string country = "CAN")
{
// Here you create your parameters to be added to the request content
var postParams = new Dictionary<string, string> { { "cardNumber", cardNumber }, { "country", country } };
// make a POST request to the "cards" endpoint and pass in the parameters
return MakeRequest<CardInformation>("POST", "cards", postParams);
}