Skip to content

Instantly share code, notes, and snippets.

@nkundu
Created May 4, 2017 13:22
Show Gist options
  • Save nkundu/9317b210cfebdded2b566558bf7f4e77 to your computer and use it in GitHub Desktop.
Save nkundu/9317b210cfebdded2b566558bf7f4e77 to your computer and use it in GitHub Desktop.
Backend code for calling JSON REST API
protected static bool MakeRequest(string uri, string method, out string message, string body = "", string accept = "application/json")
{
bool success = false;
message = "";
var body_data = Encoding.ASCII.GetBytes(body);
string req = uri;
var webRequest = (HttpWebRequest)WebRequest.Create(req);
webRequest.Method = method;
webRequest.ContentType = "application/json";
webRequest.Accept = accept;
webRequest.ContentLength = body_data.Length;
webRequest.Headers.Add(HttpRequestHeader.Authorization, "Basic xxx");
if (body_data.Length > 0)
{
using (var stream = webRequest.GetRequestStream())
{
stream.Write(body_data, 0, body_data.Length);
}
}
try
{
using (var webResponse = (HttpWebResponse)webRequest.GetResponse())
{
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
{
string s = reader.ReadToEnd();
reader.Close();
message = s;
success = webResponse.StatusCode == HttpStatusCode.OK /*|| webResponse.StatusCode == HttpStatusCode.Created*/;
}
}
}
catch (WebException e)
{
using (var webResponse = (HttpWebResponse)e.Response)
{
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
{
string s = reader.ReadToEnd();
reader.Close();
message = s;
success = false;
}
}
}
catch (Exception e)
{
message = e.Message;
success = false;
}
return success;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment