Skip to content

Commit b051b23

Browse files
author
Michael Hallett
committed
Added support to allow the user to set the parameter encoding on the RestClient for restsharp#608; Code cleanup;
1 parent ec34e04 commit b051b23

File tree

7 files changed

+233
-245
lines changed

7 files changed

+233
-245
lines changed

RestSharp/Http.Async.cs

+16-16
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ namespace RestSharp
4040
/// </summary>
4141
public partial class Http
4242
{
43-
private TimeOutState _timeoutState;
43+
private TimeOutState timeoutState;
4444

4545
public HttpWebRequest DeleteAsync(Action<HttpResponse> action)
4646
{
@@ -129,11 +129,11 @@ private HttpWebRequest GetStyleMethodInternalAsync(string method, Action<HttpRes
129129
}
130130
else
131131
{
132-
_timeoutState = new TimeOutState { Request = webRequest };
132+
this.timeoutState = new TimeOutState { Request = webRequest };
133133

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

136-
SetTimeout(asyncResult, _timeoutState);
136+
SetTimeout(asyncResult, this.timeoutState);
137137
}
138138
}
139139
catch (Exception ex)
@@ -151,7 +151,7 @@ private HttpResponse CreateErrorResponse(Exception ex)
151151

152152
if (webException != null && webException.Status == WebExceptionStatus.RequestCanceled)
153153
{
154-
response.ResponseStatus = _timeoutState.TimedOut ? ResponseStatus.TimedOut : ResponseStatus.Aborted;
154+
response.ResponseStatus = this.timeoutState.TimedOut ? ResponseStatus.TimedOut : ResponseStatus.Aborted;
155155
return response;
156156
}
157157

@@ -182,7 +182,7 @@ private HttpWebRequest PutPostInternalAsync(string method, Action<HttpResponse>
182182
private void WriteRequestBodyAsync(HttpWebRequest webRequest, Action<HttpResponse> callback)
183183
{
184184
IAsyncResult asyncResult;
185-
_timeoutState = new TimeOutState { Request = webRequest };
185+
this.timeoutState = new TimeOutState { Request = webRequest };
186186

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

199-
SetTimeout(asyncResult, _timeoutState);
199+
SetTimeout(asyncResult, this.timeoutState);
200200
}
201201

202202
private long CalculateContentLength()
@@ -206,33 +206,33 @@ private long CalculateContentLength()
206206

207207
if (!HasFiles && !AlwaysMultipartFormData)
208208
{
209-
return _defaultEncoding.GetByteCount(RequestBody);
209+
return encoding.GetByteCount(RequestBody);
210210
}
211211

212212
// calculate length for multipart form
213213
long length = 0;
214214

215215
foreach (var file in Files)
216216
{
217-
length += _defaultEncoding.GetByteCount(GetMultipartFileHeader(file));
217+
length += this.Encoding.GetByteCount(GetMultipartFileHeader(file));
218218
length += file.ContentLength;
219-
length += _defaultEncoding.GetByteCount(_lineBreak);
219+
length += this.Encoding.GetByteCount(LINE_BREAK);
220220
}
221221

222222
foreach (var param in Parameters)
223223
{
224-
length += _defaultEncoding.GetByteCount(GetMultipartFormData(param));
224+
length += this.Encoding.GetByteCount(GetMultipartFormData(param));
225225
}
226226

227-
length += _defaultEncoding.GetByteCount(GetMultipartFooter());
227+
length += this.Encoding.GetByteCount(GetMultipartFooter());
228228
return length;
229229
}
230230

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

235-
if (_timeoutState.TimedOut)
235+
if (this.timeoutState.TimedOut)
236236
{
237237
var response = new HttpResponse { ResponseStatus = ResponseStatus.TimedOut };
238238
ExecuteCallback(response, callback);
@@ -265,7 +265,7 @@ private void RequestStreamCallback(IAsyncResult result, Action<HttpResponse> cal
265265
}
266266

267267
IAsyncResult asyncResult = webRequest.BeginGetResponse(r => ResponseCallback(r, callback), webRequest);
268-
SetTimeout(asyncResult, _timeoutState);
268+
SetTimeout(asyncResult, this.timeoutState);
269269
}
270270

271271
private void SetTimeout(IAsyncResult asyncResult, TimeOutState timeOutState)
@@ -349,7 +349,7 @@ private void ResponseCallback(IAsyncResult result, Action<HttpResponse> callback
349349

350350
try
351351
{
352-
if (_timeoutState.TimedOut)
352+
if (this.timeoutState.TimedOut)
353353
{
354354
response.ResponseStatus = ResponseStatus.TimedOut;
355355
ExecuteCallback(response, callback);
@@ -376,12 +376,12 @@ private static void ExecuteCallback(HttpResponse response, Action<HttpResponse>
376376
partial void AddAsyncHeaderActions()
377377
{
378378
#if SILVERLIGHT
379-
_restrictedHeaderActions.Add("Content-Length", (r, v) => r.ContentLength = Convert.ToInt64(v));
379+
restrictedHeaderActions.Add("Content-Length", (r, v) => r.ContentLength = Convert.ToInt64(v));
380380
#endif
381381
#if WINDOWS_PHONE
382382
// WP7 doesn't as of Beta doesn't support a way to set Content-Length either directly
383383
// or indirectly
384-
_restrictedHeaderActions.Add("Content-Length", (r, v) => { });
384+
restrictedHeaderActions.Add("Content-Length", (r, v) => { });
385385
#endif
386386
}
387387

RestSharp/Http.Sync.cs

+8-8
Original file line numberDiff line numberDiff line change
@@ -148,13 +148,13 @@ private HttpResponse PostPutInternal(string method)
148148

149149
partial void AddSyncHeaderActions()
150150
{
151-
_restrictedHeaderActions.Add("Connection", (r, v) => r.Connection = v);
152-
_restrictedHeaderActions.Add("Content-Length", (r, v) => r.ContentLength = Convert.ToInt64(v));
153-
_restrictedHeaderActions.Add("Expect", (r, v) => r.Expect = v);
154-
_restrictedHeaderActions.Add("If-Modified-Since", (r, v) => r.IfModifiedSince = Convert.ToDateTime(v));
155-
_restrictedHeaderActions.Add("Referer", (r, v) => r.Referer = v);
156-
_restrictedHeaderActions.Add("Transfer-Encoding", (r, v) => { r.TransferEncoding = v; r.SendChunked = true; });
157-
_restrictedHeaderActions.Add("User-Agent", (r, v) => r.UserAgent = v);
151+
restrictedHeaderActions.Add("Connection", (r, v) => r.Connection = v);
152+
restrictedHeaderActions.Add("Content-Length", (r, v) => r.ContentLength = Convert.ToInt64(v));
153+
restrictedHeaderActions.Add("Expect", (r, v) => r.Expect = v);
154+
restrictedHeaderActions.Add("If-Modified-Since", (r, v) => r.IfModifiedSince = Convert.ToDateTime(v));
155+
restrictedHeaderActions.Add("Referer", (r, v) => r.Referer = v);
156+
restrictedHeaderActions.Add("Transfer-Encoding", (r, v) => { r.TransferEncoding = v; r.SendChunked = true; });
157+
restrictedHeaderActions.Add("User-Agent", (r, v) => r.UserAgent = v);
158158
}
159159

160160
private void ExtractErrorResponse(HttpResponse httpResponse, Exception ex)
@@ -234,7 +234,7 @@ private void WriteRequestBody(HttpWebRequest webRequest)
234234
if (!HasBody)
235235
return;
236236

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

239239
webRequest.ContentLength = bytes.Length;
240240

RestSharp/Http.cs

+27-25
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,7 @@ namespace RestSharp
3434
/// </summary>
3535
public partial class Http : IHttp, IHttpFactory
3636
{
37-
private const string _lineBreak = "\r\n";
38-
private static readonly Encoding _defaultEncoding = Encoding.UTF8;
37+
private const string LINE_BREAK = "\r\n";
3938

4039
///<summary>
4140
/// Creates an IHttp
@@ -148,6 +147,9 @@ protected bool HasFiles
148147
/// </summary>
149148
public bool UseDefaultCredentials { get; set; }
150149
#endif
150+
private Encoding encoding = Encoding.UTF8;
151+
152+
public Encoding Encoding { get { return this.encoding; } set { this.encoding = value; } }
151153

152154
/// <summary>
153155
/// HTTP headers to be sent with request
@@ -201,15 +203,15 @@ protected bool HasFiles
201203
/// </summary>
202204
public Http()
203205
{
204-
Headers = new List<HttpHeader>();
205-
Files = new List<HttpFile>();
206-
Parameters = new List<HttpParameter>();
207-
Cookies = new List<HttpCookie>();
206+
this.Headers = new List<HttpHeader>();
207+
this.Files = new List<HttpFile>();
208+
this.Parameters = new List<HttpParameter>();
209+
this.Cookies = new List<HttpCookie>();
208210

209-
_restrictedHeaderActions = new Dictionary<string, Action<HttpWebRequest, string>>(StringComparer.OrdinalIgnoreCase);
211+
restrictedHeaderActions = new Dictionary<string, Action<HttpWebRequest, string>>(StringComparer.OrdinalIgnoreCase);
210212

211-
AddSharedHeaderActions();
212-
AddSyncHeaderActions();
213+
this.AddSharedHeaderActions();
214+
this.AddSyncHeaderActions();
213215
}
214216

215217
partial void AddSyncHeaderActions();
@@ -218,10 +220,10 @@ public Http()
218220

219221
private void AddSharedHeaderActions()
220222
{
221-
_restrictedHeaderActions.Add("Accept", (r, v) => r.Accept = v);
222-
_restrictedHeaderActions.Add("Content-Type", (r, v) => r.ContentType = v);
223+
restrictedHeaderActions.Add("Accept", (r, v) => r.Accept = v);
224+
restrictedHeaderActions.Add("Content-Type", (r, v) => r.ContentType = v);
223225
#if NET4
224-
_restrictedHeaderActions.Add("Date", (r, v) =>
226+
restrictedHeaderActions.Add("Date", (r, v) =>
225227
{
226228
DateTime parsed;
227229

@@ -231,14 +233,14 @@ private void AddSharedHeaderActions()
231233
}
232234
});
233235

234-
_restrictedHeaderActions.Add("Host", (r, v) => r.Host = v);
236+
restrictedHeaderActions.Add("Host", (r, v) => r.Host = v);
235237
#else
236-
_restrictedHeaderActions.Add("Date", (r, v) => { /* Set by system */ });
237-
_restrictedHeaderActions.Add("Host", (r, v) => { /* Set by system */ });
238+
restrictedHeaderActions.Add("Date", (r, v) => { /* Set by system */ });
239+
restrictedHeaderActions.Add("Host", (r, v) => { /* Set by system */ });
238240
#endif
239241

240242
#if FRAMEWORK
241-
_restrictedHeaderActions.Add("Range", (r, v) => { AddRange(r, v); });
243+
restrictedHeaderActions.Add("Range", (r, v) => { AddRange(r, v); });
242244
#endif
243245
}
244246

@@ -252,7 +254,7 @@ private static string GetMultipartFormContentType()
252254
private static string GetMultipartFileHeader(HttpFile file)
253255
{
254256
return string.Format("--{0}{4}Content-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"{4}Content-Type: {3}{4}{4}",
255-
FormBoundary, file.Name, file.FileName, file.ContentType ?? "application/octet-stream", _lineBreak);
257+
FormBoundary, file.Name, file.FileName, file.ContentType ?? "application/octet-stream", LINE_BREAK);
256258
}
257259

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

264-
return string.Format(format, FormBoundary, param.Name, param.Value, _lineBreak);
266+
return string.Format(format, FormBoundary, param.Name, param.Value, LINE_BREAK);
265267
}
266268

267269
private static string GetMultipartFooter()
268270
{
269-
return string.Format("--{0}--{1}", FormBoundary, _lineBreak);
271+
return string.Format("--{0}--{1}", FormBoundary, LINE_BREAK);
270272
}
271273

272-
private readonly IDictionary<string, Action<HttpWebRequest, string>> _restrictedHeaderActions;
274+
private readonly IDictionary<string, Action<HttpWebRequest, string>> restrictedHeaderActions;
273275

274276
// handle restricted headers the .NET way - thanks @dimebrain!
275277
// http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.headers.aspx
276278
private void AppendHeaders(HttpWebRequest webRequest)
277279
{
278280
foreach (var header in Headers)
279281
{
280-
if (_restrictedHeaderActions.ContainsKey(header.Name))
282+
if (restrictedHeaderActions.ContainsKey(header.Name))
281283
{
282-
_restrictedHeaderActions[header.Name].Invoke(webRequest, header.Value);
284+
restrictedHeaderActions[header.Name].Invoke(webRequest, header.Value);
283285
}
284286
else
285287
{
@@ -356,9 +358,9 @@ private void PreparePostBody(HttpWebRequest webRequest)
356358
}
357359
}
358360

359-
private static void WriteStringTo(Stream stream, string toWrite)
361+
private void WriteStringTo(Stream stream, string toWrite)
360362
{
361-
var bytes = _defaultEncoding.GetBytes(toWrite);
363+
var bytes = this.Encoding.GetBytes(toWrite);
362364
stream.Write(bytes, 0, bytes.Length);
363365
}
364366

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

377379
// Write the file data directly to the Stream, rather than serializing it to a string.
378380
file.Writer(requestStream);
379-
WriteStringTo(requestStream, _lineBreak);
381+
WriteStringTo(requestStream, LINE_BREAK);
380382
}
381383

382384
WriteStringTo(requestStream, GetMultipartFooter());

RestSharp/IHttp.cs

+3
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
using System.IO;
2020
using System.Net;
2121
using System.Security.Cryptography.X509Certificates;
22+
using System.Text;
2223

2324
namespace RestSharp
2425
{
@@ -57,6 +58,8 @@ public interface IHttp
5758
bool UseDefaultCredentials { get; set; }
5859
#endif
5960

61+
Encoding Encoding { get; set; }
62+
6063
IList<HttpHeader> Headers { get; }
6164

6265
IList<HttpParameter> Parameters { get; }

RestSharp/IRestClient.cs

+4-40
Original file line numberDiff line numberDiff line change
@@ -18,76 +18,40 @@
1818
using System.Net;
1919
using System.Collections.Generic;
2020
using System.Security.Cryptography.X509Certificates;
21+
using System.Text;
22+
2123
#if NET4 || MONODROID || MONOTOUCH || WP8
2224
using System.Threading;
2325
using System.Threading.Tasks;
2426
#endif
2527

2628
namespace RestSharp
2729
{
28-
/// <summary>
29-
///
30-
/// </summary>
3130
public interface IRestClient
3231
{
33-
/// <summary>
34-
///
35-
/// </summary>
3632
#if !PocketPC
3733
CookieContainer CookieContainer { get; set; }
3834
#endif
39-
/// <summary>
40-
///
41-
/// </summary>
4235
string UserAgent { get; set; }
4336

44-
/// <summary>
45-
///
46-
/// </summary>
4737
int Timeout { get; set; }
4838

49-
/// <summary>
50-
///
51-
/// </summary>
5239
int ReadWriteTimeout { get; set; }
5340

54-
/// <summary>
55-
///
56-
/// </summary>
5741
bool UseSynchronizationContext { get; set; }
5842

59-
/// <summary>
60-
///
61-
/// </summary>
6243
IAuthenticator Authenticator { get; set; }
6344

64-
/// <summary>
65-
///
66-
/// </summary>
6745
Uri BaseUrl { get; set; }
6846

69-
/// <summary>
70-
///
71-
/// </summary>
47+
Encoding Encoding { get; set; }
48+
7249
bool PreAuthenticate { get; set; }
7350

74-
/// <summary>
75-
///
76-
/// </summary>
7751
IList<Parameter> DefaultParameters { get; }
7852

79-
/// <summary>
80-
///
81-
/// </summary>
82-
/// <param name="request"></param>
83-
/// <param name="callback"></param>
8453
RestRequestAsyncHandle ExecuteAsync(IRestRequest request, Action<IRestResponse, RestRequestAsyncHandle> callback);
8554

86-
/// <summary>
87-
///
88-
/// </summary>
89-
/// <param name="request"></param>
90-
/// <param name="callback"></param>
9155
RestRequestAsyncHandle ExecuteAsync<T>(IRestRequest request, Action<IRestResponse<T>, RestRequestAsyncHandle> callback);
9256

9357
#if FRAMEWORK || PocketPC

0 commit comments

Comments
 (0)