Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 18 additions & 20 deletions RestSharp/Http.Async.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
#endregion

using System;
using System.Linq;
using System.Net;
using System.Threading;
using RestSharp.Extensions;
Expand All @@ -40,7 +41,7 @@ namespace RestSharp
/// </summary>
public partial class Http
{
private TimeOutState _timeoutState;
private TimeOutState timeoutState;

public HttpWebRequest DeleteAsync(Action<HttpResponse> action)
{
Expand Down Expand Up @@ -129,11 +130,11 @@ private HttpWebRequest GetStyleMethodInternalAsync(string method, Action<HttpRes
}
else
{
_timeoutState = new TimeOutState { Request = webRequest };
this.timeoutState = new TimeOutState { Request = webRequest };

var asyncResult = webRequest.BeginGetResponse(result => ResponseCallback(result, callback), webRequest);

SetTimeout(asyncResult, _timeoutState);
SetTimeout(asyncResult, this.timeoutState);
}
}
catch (Exception ex)
Expand All @@ -151,7 +152,7 @@ private HttpResponse CreateErrorResponse(Exception ex)

if (webException != null && webException.Status == WebExceptionStatus.RequestCanceled)
{
response.ResponseStatus = _timeoutState.TimedOut ? ResponseStatus.TimedOut : ResponseStatus.Aborted;
response.ResponseStatus = this.timeoutState.TimedOut ? ResponseStatus.TimedOut : ResponseStatus.Aborted;
return response;
}

Expand Down Expand Up @@ -182,7 +183,7 @@ private HttpWebRequest PutPostInternalAsync(string method, Action<HttpResponse>
private void WriteRequestBodyAsync(HttpWebRequest webRequest, Action<HttpResponse> callback)
{
IAsyncResult asyncResult;
_timeoutState = new TimeOutState { Request = webRequest };
this.timeoutState = new TimeOutState { Request = webRequest };

if (HasBody || HasFiles || AlwaysMultipartFormData)
{
Expand All @@ -196,7 +197,7 @@ private void WriteRequestBodyAsync(HttpWebRequest webRequest, Action<HttpRespons
asyncResult = webRequest.BeginGetResponse(r => ResponseCallback(r, callback), webRequest);
}

SetTimeout(asyncResult, _timeoutState);
SetTimeout(asyncResult, this.timeoutState);
}

private long CalculateContentLength()
Expand All @@ -206,33 +207,31 @@ private long CalculateContentLength()

if (!HasFiles && !AlwaysMultipartFormData)
{
return _defaultEncoding.GetByteCount(RequestBody);
return encoding.GetByteCount(RequestBody);
}

// calculate length for multipart form
long length = 0;

foreach (var file in Files)
{
length += _defaultEncoding.GetByteCount(GetMultipartFileHeader(file));
length += this.Encoding.GetByteCount(GetMultipartFileHeader(file));
length += file.ContentLength;
length += _defaultEncoding.GetByteCount(_lineBreak);
length += this.Encoding.GetByteCount(LINE_BREAK);
}

foreach (var param in Parameters)
{
length += _defaultEncoding.GetByteCount(GetMultipartFormData(param));
}
length = this.Parameters.Aggregate(length,
(current, param) => current + this.Encoding.GetByteCount(this.GetMultipartFormData(param)));

length += _defaultEncoding.GetByteCount(GetMultipartFooter());
length += this.Encoding.GetByteCount(GetMultipartFooter());
return length;
}

private void RequestStreamCallback(IAsyncResult result, Action<HttpResponse> callback)
{
var webRequest = (HttpWebRequest)result.AsyncState;

if (_timeoutState.TimedOut)
if (this.timeoutState.TimedOut)
{
var response = new HttpResponse { ResponseStatus = ResponseStatus.TimedOut };
ExecuteCallback(response, callback);
Expand Down Expand Up @@ -265,7 +264,7 @@ private void RequestStreamCallback(IAsyncResult result, Action<HttpResponse> cal
}

IAsyncResult asyncResult = webRequest.BeginGetResponse(r => ResponseCallback(r, callback), webRequest);
SetTimeout(asyncResult, _timeoutState);
SetTimeout(asyncResult, this.timeoutState);
}

private void SetTimeout(IAsyncResult asyncResult, TimeOutState timeOutState)
Expand Down Expand Up @@ -304,7 +303,6 @@ private static void TimeoutCallback(object state, bool timedOut)

private static void GetRawResponseAsync(IAsyncResult result, Action<HttpWebResponse> callback)
{
var response = new HttpResponse { ResponseStatus = ResponseStatus.None };
HttpWebResponse raw;

try
Expand Down Expand Up @@ -349,7 +347,7 @@ private void ResponseCallback(IAsyncResult result, Action<HttpResponse> callback

try
{
if (_timeoutState.TimedOut)
if (this.timeoutState.TimedOut)
{
response.ResponseStatus = ResponseStatus.TimedOut;
ExecuteCallback(response, callback);
Expand All @@ -376,12 +374,12 @@ private static void ExecuteCallback(HttpResponse response, Action<HttpResponse>
partial void AddAsyncHeaderActions()
{
#if SILVERLIGHT
_restrictedHeaderActions.Add("Content-Length", (r, v) => r.ContentLength = Convert.ToInt64(v));
restrictedHeaderActions.Add("Content-Length", (r, v) => r.ContentLength = Convert.ToInt64(v));
#endif
#if WINDOWS_PHONE
// WP7 doesn't as of Beta doesn't support a way to set Content-Length either directly
// or indirectly
_restrictedHeaderActions.Add("Content-Length", (r, v) => { });
restrictedHeaderActions.Add("Content-Length", (r, v) => { });
#endif
}

Expand Down
16 changes: 8 additions & 8 deletions RestSharp/Http.Sync.cs
Original file line number Diff line number Diff line change
Expand Up @@ -148,13 +148,13 @@ private HttpResponse PostPutInternal(string method)

partial void AddSyncHeaderActions()
{
_restrictedHeaderActions.Add("Connection", (r, v) => r.Connection = v);
_restrictedHeaderActions.Add("Content-Length", (r, v) => r.ContentLength = Convert.ToInt64(v));
_restrictedHeaderActions.Add("Expect", (r, v) => r.Expect = v);
_restrictedHeaderActions.Add("If-Modified-Since", (r, v) => r.IfModifiedSince = Convert.ToDateTime(v));
_restrictedHeaderActions.Add("Referer", (r, v) => r.Referer = v);
_restrictedHeaderActions.Add("Transfer-Encoding", (r, v) => { r.TransferEncoding = v; r.SendChunked = true; });
_restrictedHeaderActions.Add("User-Agent", (r, v) => r.UserAgent = v);
restrictedHeaderActions.Add("Connection", (r, v) => r.Connection = v);
restrictedHeaderActions.Add("Content-Length", (r, v) => r.ContentLength = Convert.ToInt64(v));
restrictedHeaderActions.Add("Expect", (r, v) => r.Expect = v);
restrictedHeaderActions.Add("If-Modified-Since", (r, v) => r.IfModifiedSince = Convert.ToDateTime(v));
restrictedHeaderActions.Add("Referer", (r, v) => r.Referer = v);
restrictedHeaderActions.Add("Transfer-Encoding", (r, v) => { r.TransferEncoding = v; r.SendChunked = true; });
restrictedHeaderActions.Add("User-Agent", (r, v) => r.UserAgent = v);
}

private void ExtractErrorResponse(HttpResponse httpResponse, Exception ex)
Expand Down Expand Up @@ -234,7 +234,7 @@ private void WriteRequestBody(HttpWebRequest webRequest)
if (!HasBody)
return;

var bytes = RequestBodyBytes == null ? _defaultEncoding.GetBytes(RequestBody) : RequestBodyBytes;
var bytes = this.RequestBodyBytes ?? this.Encoding.GetBytes(this.RequestBody);

webRequest.ContentLength = bytes.Length;

Expand Down
56 changes: 29 additions & 27 deletions RestSharp/Http.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@ namespace RestSharp
/// </summary>
public partial class Http : IHttp, IHttpFactory
{
private const string _lineBreak = "\r\n";
private static readonly Encoding _defaultEncoding = Encoding.UTF8;
private const string LINE_BREAK = "\r\n";

///<summary>
/// Creates an IHttp
Expand Down Expand Up @@ -148,6 +147,9 @@ protected bool HasFiles
/// </summary>
public bool UseDefaultCredentials { get; set; }
#endif
private Encoding encoding = Encoding.UTF8;

public Encoding Encoding { get { return this.encoding; } set { this.encoding = value; } }

/// <summary>
/// HTTP headers to be sent with request
Expand Down Expand Up @@ -201,15 +203,15 @@ protected bool HasFiles
/// </summary>
public Http()
{
Headers = new List<HttpHeader>();
Files = new List<HttpFile>();
Parameters = new List<HttpParameter>();
Cookies = new List<HttpCookie>();
this.Headers = new List<HttpHeader>();
this.Files = new List<HttpFile>();
this.Parameters = new List<HttpParameter>();
this.Cookies = new List<HttpCookie>();

_restrictedHeaderActions = new Dictionary<string, Action<HttpWebRequest, string>>(StringComparer.OrdinalIgnoreCase);
restrictedHeaderActions = new Dictionary<string, Action<HttpWebRequest, string>>(StringComparer.OrdinalIgnoreCase);

AddSharedHeaderActions();
AddSyncHeaderActions();
this.AddSharedHeaderActions();
this.AddSyncHeaderActions();
}

partial void AddSyncHeaderActions();
Expand All @@ -218,10 +220,10 @@ public Http()

private void AddSharedHeaderActions()
{
_restrictedHeaderActions.Add("Accept", (r, v) => r.Accept = v);
_restrictedHeaderActions.Add("Content-Type", (r, v) => r.ContentType = v);
restrictedHeaderActions.Add("Accept", (r, v) => r.Accept = v);
restrictedHeaderActions.Add("Content-Type", (r, v) => r.ContentType = v);
#if NET4
_restrictedHeaderActions.Add("Date", (r, v) =>
restrictedHeaderActions.Add("Date", (r, v) =>
{
DateTime parsed;

Expand All @@ -231,28 +233,28 @@ private void AddSharedHeaderActions()
}
});

_restrictedHeaderActions.Add("Host", (r, v) => r.Host = v);
restrictedHeaderActions.Add("Host", (r, v) => r.Host = v);
#else
_restrictedHeaderActions.Add("Date", (r, v) => { /* Set by system */ });
_restrictedHeaderActions.Add("Host", (r, v) => { /* Set by system */ });
restrictedHeaderActions.Add("Date", (r, v) => { /* Set by system */ });
restrictedHeaderActions.Add("Host", (r, v) => { /* Set by system */ });
#endif

#if FRAMEWORK
_restrictedHeaderActions.Add("Range", (r, v) => { AddRange(r, v); });
restrictedHeaderActions.Add("Range", (r, v) => { AddRange(r, v); });
#endif
}

private const string FormBoundary = "-----------------------------28947758029299";
private const string FORM_BOUNDARY = "-----------------------------28947758029299";

private static string GetMultipartFormContentType()
{
return string.Format("multipart/form-data; boundary={0}", FormBoundary);
return string.Format("multipart/form-data; boundary={0}", FORM_BOUNDARY);
}

private static string GetMultipartFileHeader(HttpFile file)
{
return string.Format("--{0}{4}Content-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"{4}Content-Type: {3}{4}{4}",
FormBoundary, file.Name, file.FileName, file.ContentType ?? "application/octet-stream", _lineBreak);
FORM_BOUNDARY, file.Name, file.FileName, file.ContentType ?? "application/octet-stream", LINE_BREAK);
}

private string GetMultipartFormData(HttpParameter param)
Expand All @@ -261,25 +263,25 @@ private string GetMultipartFormData(HttpParameter param)
? "--{0}{3}Content-Type: {1}{3}Content-Disposition: form-data; name=\"{1}\"{3}{3}{2}{3}"
: "--{0}{3}Content-Disposition: form-data; name=\"{1}\"{3}{3}{2}{3}";

return string.Format(format, FormBoundary, param.Name, param.Value, _lineBreak);
return string.Format(format, FORM_BOUNDARY, param.Name, param.Value, LINE_BREAK);
}

private static string GetMultipartFooter()
{
return string.Format("--{0}--{1}", FormBoundary, _lineBreak);
return string.Format("--{0}--{1}", FORM_BOUNDARY, LINE_BREAK);
}

private readonly IDictionary<string, Action<HttpWebRequest, string>> _restrictedHeaderActions;
private readonly IDictionary<string, Action<HttpWebRequest, string>> restrictedHeaderActions;

// handle restricted headers the .NET way - thanks @dimebrain!
// http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.headers.aspx
private void AppendHeaders(HttpWebRequest webRequest)
{
foreach (var header in Headers)
{
if (_restrictedHeaderActions.ContainsKey(header.Name))
if (restrictedHeaderActions.ContainsKey(header.Name))
{
_restrictedHeaderActions[header.Name].Invoke(webRequest, header.Value);
restrictedHeaderActions[header.Name].Invoke(webRequest, header.Value);
}
else
{
Expand Down Expand Up @@ -356,9 +358,9 @@ private void PreparePostBody(HttpWebRequest webRequest)
}
}

private static void WriteStringTo(Stream stream, string toWrite)
private void WriteStringTo(Stream stream, string toWrite)
{
var bytes = _defaultEncoding.GetBytes(toWrite);
var bytes = this.Encoding.GetBytes(toWrite);
stream.Write(bytes, 0, bytes.Length);
}

Expand All @@ -376,7 +378,7 @@ private void WriteMultipartFormData(Stream requestStream)

// Write the file data directly to the Stream, rather than serializing it to a string.
file.Writer(requestStream);
WriteStringTo(requestStream, _lineBreak);
WriteStringTo(requestStream, LINE_BREAK);
}

WriteStringTo(requestStream, GetMultipartFooter());
Expand Down
3 changes: 3 additions & 0 deletions RestSharp/IHttp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
using System.IO;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace RestSharp
{
Expand Down Expand Up @@ -57,6 +58,8 @@ public interface IHttp
bool UseDefaultCredentials { get; set; }
#endif

Encoding Encoding { get; set; }

IList<HttpHeader> Headers { get; }

IList<HttpParameter> Parameters { get; }
Expand Down
Loading