HttpWebRequest Vs HttpClient - PullRequest
       22

HttpWebRequest Vs HttpClient

6 голосов
/ 10 мая 2011

У меня есть кусок кода, который работает с использованием HttpWebRequest и HttpWebResponse , но я хотел бы преобразовать его для использования HttpClient и 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 не присоединяется правильно (возможно).

Ответы [ 2 ]

1 голос
/ 11 мая 2011

Мне бы хотелось узнать причину, по которой один подход не работает, а другой работает, но у меня просто нет времени больше копать.{: 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;
}

Спасибо.

1 голос
/ 11 мая 2011

Метод HttpClient.Post имеет перегрузку, которая принимает параметр contentType, попробуйте это:

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