//-----------------------------------------------------------------------
//
// Copyright (c) Andrew Arnott. All rights reserved.
//
//-----------------------------------------------------------------------
namespace DotNetOAuth.ChannelElements {
using System;
using System.IO;
using System.Net;
using DotNetOAuth.Messaging;
///
/// The default handler for transmitting instances
/// and returning the responses.
///
internal class StandardWebRequestHandler : IWebRequestHandler {
#region IWebRequestHandler Members
///
/// Prepares a POST and returns the request stream
/// for writing out the POST entity data.
///
/// The that should contain the entity.
/// The stream the caller should write out the entity data to.
public TextWriter GetRequestStream(HttpWebRequest request) {
if (request == null) {
throw new ArgumentNullException("request");
}
try {
return new StreamWriter(request.GetRequestStream());
} catch (WebException ex) {
throw new ProtocolException(MessagingStrings.ErrorInRequestReplyMessage, ex);
}
}
///
/// Processes an and converts the
/// to a instance.
///
/// The to handle.
/// An instance of describing the response.
public Response GetResponse(HttpWebRequest request) {
if (request == null) {
throw new ArgumentNullException("request");
}
try {
Logger.DebugFormat("HTTP {0} {1}", request.Method, request.RequestUri);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
return new Response(response);
}
} catch (WebException ex) {
if (Logger.IsErrorEnabled) {
if (ex.Response != null) {
using (var reader = new StreamReader(ex.Response.GetResponseStream())) {
Logger.ErrorFormat("WebException from {0}: {1}", ex.Response.ResponseUri, reader.ReadToEnd());
}
} else {
Logger.ErrorFormat("WebException {1} from {0}, no response available.", request.RequestUri, ex.Status);
}
}
throw new ProtocolException(MessagingStrings.ErrorInRequestReplyMessage, ex);
}
}
#endregion
}
}