如何在Windows Phone 8中使用HttpClient请求发送Post请求体?
如何在Windows Phone 8中使用HttpClient请求发送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();
admin 更改状态以发布 2023年5月24日
我是用以下方法来实现的。我想要一个通用的MakeRequest
方法,它可以调用我的API,并接收请求体中的内容,同时将响应反序列化为所需的类型。我创建了一个Dictionary
对象来存储要提交的内容,然后将HttpRequestMessage
的Content
属性设置为它:
调用API的通用方法:
private static T MakeRequest(string httpMethod, string route, Dictionary 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 (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{ { "cardNumber", cardNumber }, { "country", country } }; // make a POST request to the "cards" endpoint and pass in the parameters return MakeRequest ("POST", "cards", postParams); }
更新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
是您的编码内容。您还应该包括正确的Content-type头。