Created
August 5, 2011 09:29
-
-
Save SergXIIIth/1127194 to your computer and use it in GitHub Desktop.
c# curl or rest client
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 System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Web; | |
using System.Net; | |
using System.Text; | |
using System.IO; | |
namespace Website.Model | |
{ | |
public class Curl | |
{ | |
public Response response_last; | |
public class Response | |
{ | |
public Response(HttpWebResponse response) | |
{ | |
if (response == null) { | |
this.description = "response == null"; | |
this.code = HttpStatusCode.BadRequest; | |
} | |
else { | |
this.description = response.StatusDescription; | |
this.code = response.StatusCode; | |
} | |
} | |
public string description { get; set; } | |
public HttpStatusCode code { get; set; } | |
public bool unsuccess { get { return code != HttpStatusCode.OK; } } | |
public override string ToString() | |
{ | |
return ((int)code).ToString() + " - " + description; | |
} | |
} | |
public string post(string url, Dictionary<string, string> data) | |
{ | |
var request = WebRequest.Create(url); | |
request.Method = "POST"; | |
request.ContentType = "application/x-www-form-urlencoded"; | |
StringBuilder data_str = new StringBuilder(); | |
foreach (var _d in data) { | |
data_str.Append(_d.Key + "=" + HttpUtility.UrlEncode(_d.Value)); | |
} | |
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data_str.ToString()); | |
// Set the content length in the request headers | |
request.ContentLength = byteData.Length; | |
// Write data | |
using (Stream postStream = request.GetRequestStream()) { | |
postStream.Write(byteData, 0, byteData.Length); | |
} | |
try { | |
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { | |
response_last = new Response(response); | |
// Get the response stream | |
StreamReader reader = new StreamReader(response.GetResponseStream()); | |
return reader.ReadToEnd(); | |
} | |
} | |
catch (WebException wex) { | |
if (wex.Response == null) { | |
response_last = new Response(null); | |
return ""; | |
} | |
using (HttpWebResponse errorResponse = (HttpWebResponse)wex.Response) { | |
response_last = new Response(errorResponse); | |
StreamReader reader = new StreamReader(errorResponse.GetResponseStream(), Encoding.UTF8); | |
return reader.ReadToEnd(); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment