HttpWebRequest против HttpClient

У меня есть фрагмент кода, который работает с использованием 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 прикрепляется неправильно (возможно). std :: tr1 :: shared_ptr

Я хотел бы использовать библиотеки TR1, которые поставляются с современными версиями GCC и MSVC, но есть тонкие различия: в GCC я должен сказать

#include <tr1/memory>
std::tr1::shared_ptr<int> X;

, а в MSVC я должен сказать

#include <memory>
std::shared_ptr<int> X;

У меня есть два вопроса: 1) MSVC автоматически работает в C ++ 0x-режиме (эквивалентном GCC std = c ++ 0x), или он также работает в C ++ 98 / 03 режим по умолчанию? 2) Как я могу объединить включаемые пространства и пространства имен? Я думал о макросе препроцессора типа «INCLUDE_TR1 (память)» или о чем-то подобном.

Чтобы прояснить, я хочу использовать традиционный, стандартный C ++ 98/03; не C ++ 0x (иначе не было бы проблем).

Буду очень признателен за любые предложения!

10
задан Kerrek SB 10 May 2011 в 15:34
поделиться