开发者

Efficent way of retrieveing HttpWebResponse and putting it in XDocument

There is a local service from which I need to consume a generated XML Document Stream. Though the end point is not a REST service per se. I wanted to be sure the method I've outlined below is the most efficient way of getting the response returned into an XDocument.

Uri requestUri = null;
Uri.TryCreate(String.Format(SearchAddress, filter),
    UriKind.Absolute, out requestUri);

NetworkCredential nc =开发者_如何学编程
    new NetworkCredential("Login", "Password");
CredentialCache cCache = new CredentialCache();
cCache.Add(requestUri, "Basic", nc);

HttpWebRequest request =
    (HttpWebRequest)HttpWebRequest.Create(requestUri);
request.Credentials = cCache;
request.PreAuthenticate = true;
request.Method = WebRequestMethods.Http.Get;

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
XDocument xDoc =
    XDocument.Load(new StreamReader(response.GetResponseStream()));


If you want a synchronous request then in my opinion yes it is.

But it would be a good idea to handle WebException. In WebException.Response.GetResponseStream() you should have either a HTTP/HTML error page or a soapfault.

Asynch request
// starts asynch retrieval of response stream...
var result = request.BeginGetResponse(...)
// setting a timeout callback method, BeginGetResponse doesn´t timeout...
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, ...)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜