c# - HttpWebRequest 与 HttpClient

标签 c# wcf httpwebrequest httpclient

我有一段代码可以使用 HttpWebRequestHttpWebResponse 但我想将其转换为使用 HttpClient 和 < strong>HttpResponseMessage.

这是有效的代码块......

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(serviceReq);

request.Method = "POST";
request.ContentType = "text/xml";
string xml = @"<?xml version=""1.0""?><root><login><user>flibble</user>" + 
    @"<pwd></pwd></login></root>";
request.ContentLength = xml.Length;
using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
{
    dataStream.Write(xml);
    dataStream.Close();
}

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

这是我想要替换它的代码,如果我能让它正常工作就好了。

/// <summary>
/// Validate the user credentials held as member variables
/// </summary>
/// <returns>True if the user credentials are valid, else false</returns>
public bool ValidateUser()
{
    bool valid = false;

    try
    {
        // Create the XML to be passed as the request
        XElement root = BuildRequestXML("LOGON");

        // Add the action to the service address
        Uri serviceReq = new Uri(m_ServiceAddress + "?obj=LOGON");


        // Create the client for the request to be sent from
        using (HttpClient client = new HttpClient())
        {
            // Initalise a response object
            HttpResponseMessage response = null;

            // Create a content object for the request
            HttpContent content = HttpContentExtensions.
                CreateDataContract<XElement>(root);

            // Make the request and retrieve the response
            response = client.Post(serviceReq, content);

            // Throw an exception if the response is not a 200 level response
            response.EnsureStatusIsSuccessful();

            // Retrieve the content of the response for processing
            response.Content.LoadIntoBuffer();

            // TODO: parse the response string for the required data
            XElement retElement = response.Content.ReadAsXElement();
        }
    }
    catch (Exception ex)
    {
        Log.WriteLine(Category.Serious, 
            "Unable to validate the Credentials", ex);
        valid = false;
        m_uid = string.Empty;
    }

    return valid;
}

我认为问题出在创建内容对象和 XML 未正确附加(可能)。

最佳答案

HttpClient.Post 方法有一个带有 contentType 参数的重载,试试这个:

// Make the request and retrieve the response
response = client.Post(serviceReq, "text/xml", content);

关于c# - HttpWebRequest 与 HttpClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5952597/

相关文章:

c# - Visual Studio 2010的Bootstrapper Manifest Generator

C# CefSharp 离屏鼠标事件、键盘事件模拟示例

c# - 使用 linq 检查是否不存在子句

c# - 发布到发送 NULL 值的 WCF 服务

php - POST 可以进行 SQL 注入(inject)吗?

私有(private)成员变量的 C# 编码标准

c# - WCF + EF6 防止引用程序集中的枚举被序列化

c# - 从 Dotnet Core 调用 WCF 服务

c# - 为什么我的内存使用量在停止下载后激增?

C# JSON 解析与子字符串