首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > asp.net >

C#异步请求Hotmail的有关问题

2012-01-12 
C#异步请求Hotmail的问题参考了网上的资料,自己写了一段异步连接Hotmail的代码,调试中,总发现401错误(未经

C#异步请求Hotmail的问题
参考了网上的资料,自己写了一段异步连接Hotmail的代码,调试中,总发现401错误(未经授权),全部代码如下:

public   class   HotmailProxy
{
private   ManualResetEvent   _allDone;//异步操作是否完成
private   const   int   _timeOut   =   30   *   1000;//30秒超时
private   string   _request;//请求字符串
private   string   _requestMethod;//请求方法
private   Uri   _destination;//目的地
private   NetworkCredential   _credential;//包含用户名/密码
private   CookieContainer   ckContainer;//包含Cookie的容器

//----------------------入口,调用该方法报401错误---------------------------------------------
public   string   Connect(string   username,   string   password)
{
                        //HotMail入口
                        string   hotmailEntryPoint   =   "http://services.msn.com/svcs/hotmail/httpmail.asp ";
                        Uri   des   =   new   Uri(hotmailEntryPoint);

hHttp   =   new   HotmailProxy(username,   password);


//获取根文件夹查询
      string   query   =   " ";
                        query   +=   " <?xml   version= '1.0 '?> ";
query   +=   " <D:propfind   xmlns:D= 'DAV: '   xmlns:h= 'http://schemas.microsoft.com/hotmail/ '   xmlns:hm= 'urn:schemas:httpmail: '> ";
query   +=           " <D:prop> ";
query   +=                   " <hm:msgfolderroot/> ";
query   +=           " </D:prop> ";
query   +=   " </D:propfind> ";

                      string   response   =   hHttp.AsyncSendRequest(query,   "PROPFIND ",   des);
                        //   验证响应
                        if   (response   ==   null   ||   response.Trim().Length   ==   0)
                                throw   new   ApplicationException( "No   response   received   from   host. ");

                        return   response;
}


public   HotmailProxy(string   userName,   string   password)
{
_credential   =   new   NetworkCredential(userName,   password);
_allDone   =   new   ManualResetEvent(false);
ckContainer   =   new   CookieContainer();
}

public   string   AsyncSendRequest(string   request,   string   method,   Uri   destination)
{
return   this.AsyncSendRequest(request,   method,   destination,   _credential);
}

private   string   AsyncSendRequest(string   request,   string   requestMethod,   Uri   destination,   NetworkCredential   credential)


{
//全局变量赋值
_request   =   request;
_requestMethod   =   requestMethod;
_destination   =   destination;

                    //将请求转换成字节流
                    byte[]   requestBytes   =   System.Text.Encoding.ASCII.GetBytes(request);

                    //构建HttpWebRequest,   没有添加Cookie
                    HttpWebRequest   webReq   =   this.BuildWebRequest(requestMethod,   requestBytes,   destination,   credential);

          //重置状态
          _allDone.Reset();

                    //   请求写入缓冲区
                    Stream   reqStream   =   webReq.GetRequestStream();
                    reqStream.Write(requestBytes,   0,   requestBytes.Length);
                    reqStream.Close();

                    //调用RequestState
                    RequestState   rs   =   new   RequestState();
                    rs.WebRequest   =   webReq;
                    rs.WebRequest.Credentials   =   credential;

//开始异步请求
IAsyncResult   result   =   (IAsyncResult)   webReq.BeginGetResponse(new   AsyncCallback(GetResponse_CallBack),   rs);

//处理超时
ThreadPool.RegisterWaitForSingleObject   (result.AsyncWaitHandle,   new   WaitOrTimerCallback(TimeoutCallback),   webReq,   _timeOut,   true);

//阻塞当前线程,知道收到信号
_allDone.WaitOne();

rs.WebResponse.Close();

return   rs.StrBuilder.ToString();
                }

        private   void   GetResponse_CallBack(IAsyncResult   result)
{
//获取状态
RequestState   rs   =   (RequestState)   result.AsyncState;
HttpWebResponse   response   =   (HttpWebResponse)   rs.WebRequest.EndGetResponse(result);
rs.WebResponse   =   response;

//获取响应的的数据
Stream   stream   =   response.GetResponseStream();
StreamReader   sr   =   new   StreamReader(stream);
rs.StrBuilder.Append(sr.ReadToEnd());
stream.Close();
sr.Close();

//如果异步操作未完成,继续获取响应
if(   !   result.IsCompleted)
{
HttpWebRequest   webReq   =   rs.WebRequest;

//开始异步请求响应
IAsyncResult   result1   =   (IAsyncResult)   webReq.BeginGetResponse(new   AsyncCallback(GetResponse_CallBack),   rs);
}
else
{
//添加Cookie
foreach(Cookie   retCookie   in   response.Cookies)
{
bool   cookieFound   =   false;

foreach(Cookie   oldCookie   in   ckContainer.GetCookies(_destination))
{
if   (retCookie.Name.Equals(oldCookie.Name))


{
oldCookie.Value   =   retCookie.Value;
cookieFound   =   true;
}
}
if   (!cookieFound)
ckContainer.Add(retCookie);
}

//如果要求重定向
if((response.StatusCode   ==   HttpStatusCode.Found)   ||   (response.StatusCode   ==   HttpStatusCode.Redirect)   ||   (response.StatusCode   ==   HttpStatusCode.Moved)   ||   (response.StatusCode   ==   HttpStatusCode.MovedPermanently))
{
WebHeaderCollection   headers   =   response.Headers;
//获取Hotmail重新定向到的空闲服务器
_destination   =   new   Uri(headers[ "location "]);
//重新调用AsyncSendRequestTo
        AsyncSendRequest(_request,   _requestMethod,   _destination,   _credential);
}
}
}

private   HttpWebRequest   BuildWebRequest(string   RequestMethod,   byte[]   requestBytes,   Uri   destination,   NetworkCredential   credential)
                {
                        HttpWebRequest   webRequest   =   (HttpWebRequest)WebRequest.Create(destination);
                        webRequest.Method   =   RequestMethod;
                        webRequest.Accept   =   "*/* ";
                        webRequest.ContentLength   =   requestBytes.Length;
                        webRequest.AllowAutoRedirect   =   false;
                        webRequest.UserAgent   =   "Mozilla/4.0   (compatible;   MSIE   6.0;   Windows   NT   5.0;   .NET   CLR   1.0.3705) ";
                        webRequest.CookieContainer   =   new   CookieContainer();
                        webRequest.ContentType   =   "text/xml ";
                        //   Set   the   credentials
                        webRequest.Credentials   =   credential;
                        //   Add   cookies   for   this   request
                        webRequest.CookieContainer.Add(ckContainer.GetCookies(destination));
                        return   webRequest;
                }

public   class   RequestState
{
public   RequestState()
{
                        _webRequest   =   null;
                        _webResponse   =   null;
                        _strBuilder   =   new   StringBuilder();


}

                private   HttpWebRequest   _webRequest;
                public   HttpWebRequest   WebRequest
                {
                        get{return   _webRequest;}
                        set{_webRequest=value;   }
                }

                private   HttpWebResponse   _webResponse;
                public   HttpWebResponse   WebResponse
                {
                        get{return   _webResponse;}
                        set{_webResponse=value;   }
                }

                private   StringBuilder   _strBuilder;
                ///   <summary>
                ///   存储获得的数据
                ///   </summary>
                public   StringBuilder   StrBuilder
                {
                        set{_strBuilder   =   value;}
                        get{return   _strBuilder;   }
                }
}


[解决办法]
强烈关注!我也想弄一个模拟登录的功能呢。

楼主加油hanguoji84@hotmail.com
[解决办法]
努力搞好.说下啊..
[解决办法]
帮UP
[解决办法]
帮顶了..
[解决办法]
调试中,总发现401错误(未经授权)

现在hotmail可以用未经授权的客户端吗?
[解决办法]
题目一下就吸引到我 了。。  我是来学习滴~~

热点排行