summaryrefslogtreecommitdiffstats
path: root/src/DotNetOAuth/ChannelElements/StandardWebRequestHandler.cs
blob: fa91990e9d07ce12e4ef5270ba12b59289b9eff2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
//-----------------------------------------------------------------------
// <copyright file="StandardWebRequestHandler.cs" company="Andrew Arnott">
//     Copyright (c) Andrew Arnott. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace DotNetOAuth.ChannelElements {
	using System;
	using System.IO;
	using System.Net;
	using DotNetOAuth.Messaging;

	/// <summary>
	/// The default handler for transmitting <see cref="HttpWebRequest"/> instances
	/// and returning the responses.
	/// </summary>
	internal class StandardWebRequestHandler : IWebRequestHandler {
		#region IWebRequestHandler Members

		/// <summary>
		/// Prepares a POST <see cref="HttpWebRequest"/> and returns the request stream 
		/// for writing out the POST entity data.
		/// </summary>
		/// <param name="request">The <see cref="HttpWebRequest"/> that should contain the entity.</param>
		/// <returns>The stream the caller should write out the entity data to.</returns>
		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);
			}
		}

		/// <summary>
		/// Processes an <see cref="HttpWebRequest"/> and converts the 
		/// <see cref="HttpWebResponse"/> to a <see cref="Response"/> instance.
		/// </summary>
		/// <param name="request">The <see cref="HttpWebRequest"/> to handle.</param>
		/// <returns>An instance of <see cref="Response"/> describing the response.</returns>
		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
	}
}