HttpWebRequest的VS的HttpClient [英] HttpWebRequest Vs HttpClient

查看:1690
本文介绍了HttpWebRequest的VS的HttpClient的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码,工程使用的的HttpWebRequest HttpWebResponse ,但我想将其转换为使用的HttpClient 和< STRONG> HttpResponseMessage



这是该工程...



<$ p $代码块p> HttpWebRequest的要求=(HttpWebRequest的)HttpWebRequest.Create(serviceReq);

request.Method =POST;
request.ContentType =文/ XML;
串XML = @< XML版本=1.0><根><登录><使用者> flibble< /使用者名称> +
@< PWD>< /密码>< /登录>< /根>中;
request.ContentLength = xml.Length;
使用(数据流的StreamWriter =新的StreamWriter(request.GetRequestStream()))
{
dataStream.Write(XML);
dataStream.Close();
}

HttpWebResponse响应=(HttpWebResponse)request.GetResponse();



这就是我想和来取代它,只要我能得到它的代码。工作

  ///<总结> 
///验证召开成员变量
///<用户凭据; /总结>
///<退货和GT;真如果用户凭据有效,否则为假< /回报>
公共BOOL的ValidateUser()
{
布尔有效= FALSE;


{
//创建XML作为请求
的XElement根= BuildRequestXML(登录)传递;

//添加动作到服务地址
乌里serviceReq =新的URI(m_ServiceAddress +OBJ = LOGON?);


//创建客户端从
使用发送请求(HttpClient的客户端=新的HttpClient())
{
// Initalise响应对象
HttpResponseMessage响应= NULL;

//创建请求
HttpContent内容= HttpContentExtensions内容对象。
CreateDataContract<&的XElement GT;(根);

//使请求和检索响应
响应= client.Post(serviceReq,内容);如果响应是不是一个200级的响应
response.EnsureStatusIsSuccessful

//抛出异常();

//检索处理
response.Content.LoadIntoBuffer响应的内容();

// TODO:解析为所需数据
的XElement retElement = response.Content.ReadAsXElement响应字符串();
}
}
赶上(异常前)
{
Log.WriteLine(Category.Serious,
无法验证凭据,恩) ;
=有效虚假的;
m_uid =的String.Empty;
}

返回有效;
}



我认为这个问题是创建内容对象和XML是不是被正确(也许)。附


解决方案

我很想知道原因的一种方法行不通,另的确,但我就是没有任何更多的挖掘时间。 {:O(



总之,这里是我发现的



发生故障时请求的内容。使用以下



创建

  HttpContent内容= HttpContentExtensions.Create(根,Encoding.UTF8,文/ XML); 

但是,当你创建一个这样...


的内容能够正常工作

  HttpContent内容= HttpContent.Create(root.ToString(),Encoding.UTF8,文/ XML); 

最后的工作职能是这样的:

  ///<总结> 
///验证召开成员变量
///<用户凭据; /总结>
///<返回> True如果用户凭据是有效的,否则为假< /回报>
公共BOOL的ValidateUser()
{
布尔有效= FALSE;


{
//创建XML作为请求
的XElement根= BuildRequestXML(登录)传递;

//添加动作到服务地址
乌里serviceReq =新乌里(m_ServiceAddress +OBJ = LOGON?);

//创建客户端从
使用发送请求(HttpClient的客户端=新的HttpClient())
{
// Initalise响应对象
HttpResponseMessage响应= NULL;

#如果DEBUG
//强制要求使用Fiddler
client.TransportSettings.Proxy =新WebProxy(127.0.0.1,8888);
#ENDIF

//创建请求
HttpContent内容= HttpContent.Create(root.ToString(),Encoding.UTF8,文/ XML)内容对象;

//使请求和检索响应
响应= client.Post(serviceReq,内容);如果响应是不是一个200级的响应
response.EnsureStatusIsSuccessful

//抛出异常();

//检索处理
response.Content.LoadIntoBuffer响应的内容();

// TODO:解析为所需数据
的XElement retElement = response.Content.ReadAsXElement响应字符串();
}
}
赶上(异常前)
{
Log.WriteLine(Category.Serious,无法验证用户凭据,前);
=有效虚假的;
m_uid =的String.Empty;
}

返回有效;
}



感谢。


I have a chunk of code that works using a HttpWebRequest and HttpWebResponse but I'd like to convert it to use HttpClient and HttpResponseMessage.

This is the chunk of code that works...

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();

And this is the code that I'd like to replace it with, if only I could get it working.

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

I think the problem is creating the content object and the XML isn't being attached correctly (maybe).

解决方案

I'd love to know the reason why the one approach doesn't work and the other does but I just don't have the time for any more digging. {:o(

Anyway, here's what I found.

A failure occurs when the content of the request is created using the following

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

But it works correctly when you create the content like this...

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

The final working function is this:

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

Thanks.

这篇关于HttpWebRequest的VS的HttpClient的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆