using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.IO; using System.Web.Script.Serialization; using Newtonsoft.Json.Linq; namespace Nuclex.Networking.Gallery3.Requests { /// Implements a gallery request with the WebRequest class /// /// Instances of this class are usually constructed by the RequestFactory /// class, providing a WebRequest already prepared with authentication /// options or custom headers. /// public class Request : IRequest { /// Initializes a new request /// /// JSON serializer through which responses will be decoded /// /// Web request that will be used by the instance public Request(JavaScriptSerializer jsonSerializer, WebRequest webRequest) { this.jsonSerializer = jsonSerializer; this.webRequest = webRequest; } /// HTTP request method /// /// Can be "GET", "POST", "PUT" or "DELETE". Not all server support /// the "PUT" and "DELETE" methods, so these methods are passed to /// Gallery 3 as a "POST" request with a custom header: /// "X-Gallery-Request-Method". /// public string Method { get { return this.webRequest.Method; } set { this.webRequest.Method = value; } } /// The type/format of the content in a "POST" request /// /// Should be "application/x-www-form-urlencoded" for any request. /// public string ContentType { get { return this.webRequest.ContentType; } set { this.webRequest.ContentType = value; } } /// Adds a custom header field to the request /// Name of the header that will be added /// Value that will be assigned to the header field public void AddHeader(string name, string value) { this.webRequest.Headers.Add(name, value); } /// Attaches content to a POST request /// Data that will be attached to the request as content public void AttachContent(byte[] data) { this.webRequest.ContentLength = data.Length; using (Stream requestStream = this.webRequest.GetRequestStream()) { requestStream.Write(data, 0, data.Length); } } /// Sends the request to the server and returns the response /// A JSON reader through which the response can be read public ResponseType GetJsonResponse() { string json; using (WebResponse response = this.webRequest.GetResponse()) { using (Stream contentStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(contentStream); json = reader.ReadToEnd(); } } return this.jsonSerializer.Deserialize(json); } /// Actual WebRequest being wrapped by this class private WebRequest webRequest; /// JSON serializer being used to decode the response private JavaScriptSerializer jsonSerializer; } } // namespace Nuclex.Networking.Gallery3.Requests