如何在Windows Phone 8的HttpClient请求中发送Post正文
本文关键字:请求 正文 Post HttpClient Windows Phone | 更新日期: 2023-09-27 18:16:42
我已经写了下面的代码来发送头,post参数。问题是我正在使用SendAsync,因为我的请求可以是GET或POST。我如何将POST Body添加到这段代码中,以便如果有任何POST Body数据它被添加到我所做的请求中,如果它的简单GET或POST没有Body,它会以这种方式发送请求。请更新以下代码:
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();
UPDATE 2:
来自@Craig Brown:
从。net 5开始,你可以这样做:
requestMessage.Content = JsonContent.Create(new { Name = "John Doe", Age = 33 });
参见JsonContent类文档
更新1:哦,它可以更好(从这个答案):
requestMessage.Content = new StringContent("{'"name'":'"John Doe'",'"age'":33}", Encoding.UTF8, "application/json");
这取决于你有什么内容。你需要用新的HttpContent初始化你的requestMessage.Content
属性。例如:
...
// Add request body
if (isPostRequest)
{
requestMessage.Content = new ByteArrayContent(content);
}
...
其中content
是您的编码内容。您还应该包含正确的内容类型头。
我以以下方式实现它。我想要一个通用的MakeRequest
方法,它可以调用我的API并接收请求主体的内容-并且还将响应反序列化为所需的类型。我创建了一个Dictionary<string, string>
对象来存放要提交的内容,然后用它设置HttpRequestMessage
Content
属性:
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);
}
我确实创建了一个方法:
public static StringContent GetBodyJson(params (string key, string value)[] param)
{
if (param.Length == 0)
return null;
StringBuilder builder = new StringBuilder();
builder.Append(" { ");
foreach((string key, string value) in param)
{
builder.Append(" '"" + key + "'" :"); // key
builder.Append(" '"" + value + "'" ,"); // value
}
builder.Append(" } ");
return new StringContent(builder.ToString(), Encoding.UTF8, "application/json");
}
obs:在HttpContent中使用StringContent,继承的是StringContent ->ByteArrayContent→HttpContent .