2

有没有使用将 XML/json 发布到 REST 服务的工作示例HttpClient?我尝试过,但服务器返回的错误请求在语法上不正确。

  // my functions 
public T Post<T>(string method, string data)
{
    using (var httpClient = new HttpClient())
    {
        var requestMessage = GetHttpRequestMessage<string>(data);

        var result = httpClient.PostAsync(_endpoint + method, requestMessage.Content).Result;

        return result.Content.ReadAsync<T>().Result;
    }
}

protected HttpRequestMessage GetHttpRequestMessage<T>(T data, bool isJsonContent = false)
{
    var msg = new HttpRequestMessage
                  {
                      Content =
                          isJsonContent
                              ? new ObjectContent<T>(data, new JsonMediaTypeFormatter() { })
                              : new ObjectContent<T>(data, new XmlMediaTypeFormatter() { })
                  };
    return msg;
}

有没有更好的使用方法HttpClient

4

0 回答 0