Last active
September 13, 2016 12:52
-
-
Save LindaLawton/b5a31fb0c57dbcde4c68bca3b41996c6 to your computer and use it in GitHub Desktop.
For sending Generic Http POST and Http Get calls. Works with .Net 3.5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Newtonsoft.Json; | |
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using System.Net; | |
using System.Text; | |
using System.Web; | |
namespace HttpStuff | |
{ | |
public interface IHttpRequest | |
{ | |
Uri RequestUri { get; } | |
/// <summary> | |
/// Gets the endpoint. | |
/// </summary> | |
/// <value> | |
/// The endpoint. | |
/// </value> | |
Uri BaseUri { get; } | |
/// <summary> | |
/// Gets the rest path. | |
/// </summary> | |
/// <value> | |
/// The rest path. | |
/// </value> | |
string RelativePath { get; } | |
/// <summary> | |
/// Gets the method. | |
/// </summary> | |
/// <value> | |
/// The method. | |
/// </value> | |
string Method { get; } | |
/// <summary> | |
/// Gets the post data. | |
/// </summary> | |
/// <value> | |
/// The post data. | |
/// </value> | |
object PostData { get; } | |
/// <summary> | |
/// Gets the path parameters. | |
/// </summary> | |
/// <value> | |
/// The path parameters. | |
/// </value> | |
IDictionary<string, string> QueryParameters { get; } | |
/// <summary> | |
/// Adds the parameter. | |
/// </summary> | |
/// <param name="key">The key.</param> | |
/// <param name="value">The value.</param> | |
void addParameter(string key, string value); | |
} | |
public abstract class HttpRequestBase<T> : IHttpRequest | |
{ | |
public Uri RequestUri { get { return new Uri(BaseUri, RelativePath); } } | |
public Uri BaseUri { get; private set; } | |
public string RelativePath { get; set; } | |
public string Method { get; private set; } | |
public virtual object PostData { get; private set; } | |
public virtual IDictionary<string, string> QueryParameters { get; private set; } | |
public HttpRequestBase() | |
{ | |
QueryParameters = new Dictionary<string, string>(); | |
} | |
/// <summary> | |
/// Adds the parameter. UrlEncodeding the value | |
/// </summary> | |
/// <param name="key">The key.</param> | |
/// <param name="value">The value.</param> | |
public void addParameter(string key, string value) | |
{ | |
QueryParameters.Add(key, HttpUtility.UrlEncode(value)); | |
} | |
/// <summary> | |
/// Adds the post data object. | |
/// </summary> | |
/// <param name="data">The data.</param> | |
public void addPostData(object data) | |
{ | |
PostData = data; | |
} | |
/// <summary> | |
/// Initializes a new instance of the <see cref="HttpRequestBase"/> class. | |
/// </summary> | |
/// <param name="BaseUri">The base URI.</param> | |
/// <param name="RelativePath">The relative path.</param> | |
/// <param name="Method">The method.</param> | |
/// <exception cref="Exception"> | |
/// </exception> | |
public HttpRequestBase(string BaseUri, string RelativePath, string Method) : this() | |
{ | |
if (!Uri.IsWellFormedUriString(BaseUri, UriKind.Absolute)) | |
throw new Exception(string.Format("'{0}' is not a valid url host.", BaseUri)); | |
Uri outUri; | |
if (Uri.TryCreate(BaseUri, UriKind.Absolute, out outUri) && (outUri.Scheme == Uri.UriSchemeHttp || outUri.Scheme == Uri.UriSchemeHttps)) | |
{ | |
this.BaseUri = outUri; | |
} | |
else | |
{ | |
throw new Exception(string.Format("'{0}' is not a valid url.", BaseUri)); | |
} | |
this.RelativePath = RelativePath; | |
this.Method = Method; | |
} | |
/// <summary> | |
/// Initializes a new instance of the <see cref="HttpRequestBase"/> class. | |
/// </summary> | |
/// <param name="FullUri">The full Uri to call including host and AbsolutePath.</param> | |
/// <param name="Method">The method.</param> | |
public HttpRequestBase(Uri FullUri, string Method) : this(FullUri.Host, FullUri.AbsolutePath, Method) | |
{ | |
// Just passing it over to the other one no need for double code. | |
} | |
public T Execute() | |
{ | |
var request = createWebRequest(); | |
request.Method = this.Method; | |
applyPostData(ref request); | |
request.ContentType = "application/json"; | |
request.UserAgent = "generic-http-dotnet-client/3.5/v1 (gzip)"; | |
using (var response = (HttpWebResponse)request.GetResponse()) | |
{ | |
using (StreamReader reader = new StreamReader(response.GetResponseStream())) | |
{ | |
try | |
{ | |
return JsonConvert.DeserializeObject<T>(reader.ReadToEnd()); | |
} | |
catch (Exception ex) | |
{ | |
//log something with ex | |
return default(T); | |
} | |
} | |
} | |
} | |
private void applyPostData(ref HttpWebRequest request) | |
{ | |
if (PostData != null && Method.ToUpper() == "POST") | |
{ | |
var PostData = Newtonsoft.Json.JsonConvert.SerializeObject(this.PostData); | |
var data = Encoding.ASCII.GetBytes(PostData); | |
request.ContentLength = data.Length; | |
using (var stream = request.GetRequestStream()) | |
{ | |
stream.Write(data, 0, data.Length); | |
} | |
} | |
} | |
/// <summary> | |
/// Gets the query parms. Url query format. | |
/// </summary> | |
/// <returns></returns> | |
private string getQueryParms() | |
{ | |
if (QueryParameters.Count <= 0) | |
return string.Empty; | |
return "?" + string.Join("&", QueryParameters.Select(x => x.Key + "=" + x.Value).ToArray()); | |
} | |
/// <summary> | |
/// Creates the web request. | |
/// </summary> | |
/// <returns></returns> | |
private HttpWebRequest createWebRequest() | |
{ | |
return (HttpWebRequest)WebRequest.Create(new Uri(BaseUri, RelativePath + getQueryParms())); | |
} | |
} | |
public class HttpRequest<T> : HttpRequestBase<T> | |
{ | |
/// <summary> | |
/// Initializes a new instance of the <see cref="HttpRequestBase"/> class. | |
/// </summary> | |
/// <param name="FullUri">The full Uri to call including host and AbsolutePath.</param> | |
/// <param name="Method">The method.</param> | |
public HttpRequest(Uri FullUri, string Method) : base(FullUri.Scheme + "://" + FullUri.Host, FullUri.AbsolutePath, Method) | |
{ | |
if (FullUri.Query != null) | |
Console.WriteLine("Warning: Query parmaters are removed please add them using addParameter()"); | |
// Just passing it over to the other one no need for double code. | |
} | |
/// <summary> | |
/// Initializes a new instance of the <see cref="HttpRequestBase"/> class. | |
/// </summary> | |
/// <param name="BaseUri">The base URI.</param> | |
/// <param name="RelativePath">The relative path.</param> | |
/// <param name="Method">The method.</param> | |
/// <exception cref="Exception"> | |
/// </exception> | |
public HttpRequest(string BaseUri, string RelativePath, string Method) : base(BaseUri, RelativePath, Method) | |
{ | |
} | |
} | |
/// <summary> | |
/// Dummy response object | |
/// </summary> | |
public class HttpResponse | |
{ | |
/// <summary> | |
/// Gets or sets the message. | |
/// </summary> | |
/// <value> | |
/// The message. | |
/// </value> | |
public string message { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment