簡體   English   中英

HttpWebRequest與HttpClient

[英]HttpWebRequest Vs HttpClient

我有一大堆代碼使用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沒有正確附加(也許)。

HttpClient.Post方法有一個帶有contentType參數的重載,試試這個:

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

我很想知道為什么一種方法不起作用而另一種方法不起作用的原因,但我只是沒有時間進行任何挖掘。 {:○(

無論如何,這是我發現的。

使用以下內容創建請求的內容時發生故障

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;
}

謝謝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM