HttpWebRequest与HttpClient的区别

6

我有一段代码,使用了 HttpWebRequestHttpWebResponse 工作正常,但我想将其转换为使用 HttpClientHttpResponseMessage

这是工作的代码块...

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没有被正确附加(可能是这样)。


具体是什么出了问题?它无法编译吗?还是你遇到了运行时错误?是哪些错误? - fretje
请求已发送,但处理传入请求的服务认为没有数据,因此返回“未经授权访问”,这是该服务的默认响应。 - TeamWild
使用 Fiddler 并检查发送到网络的内容... - fretje
@fretje 感谢您指导我使用 Fiddler。经过很多困难,我现在已经成功地让 Fiddler 工作,并捕获了每个请求/响应的数据。有两个不同之处。工作代码在原始数据中有 <?xml version="1.0"?>,内容类型为 text/xml。不工作的代码不包括 <?xml version="1.0"?>,内容类型设置为 application/xml。我的下一步将是找出如何更改内容类型。 - TeamWild
2个回答

1

HttpClient.Post 方法有一个重载,它接受一个 contentType 参数,请尝试使用:

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

谢谢。正如您在下面看到的那样,我也有同样的思路。我遇到的问题似乎与创建内容对象的方式有关,而不是使用的发布方法。 - TeamWild

1

我很想知道为什么一种方法不起作用,而另一种方法却可以,但我没有更多时间去深入挖掘。{:o(

无论如何,这是我找到的。

当使用以下内容创建请求的内容时,会发生故障:

HttpContent content = HttpContentExtensions.Create(root, Encoding.UTF8, "text/xml");

但是如果您像这样创建内容,它将正常工作...

HttpContent content = HttpContent.Create(root.ToString(), Encoding.UTF8, "text/xml");

最终可工作的函数如下:
/// <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;

            #if DEBUG
            // Force the request to use fiddler
            client.TransportSettings.Proxy = new WebProxy("127.0.0.1", 8888);
            #endif

            // Create a content object for the request
            HttpContent content = HttpContent.Create(root.ToString(), Encoding.UTF8, "text/xml");

            // 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 user credentials", ex);
        valid = false;
        m_uid = string.Empty;
    }

    return valid;
}

谢谢。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接