JSON.NET is library for serializing and deserializing .NET objects to JSON. It has nothing to do with sending HTTP requests. You could use a WebClient
for this purpose.
For example here's how you could call the API:
string url = "http://someapi.com/extact/api/profiles/114226/pages/423833/records";
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.Authorization] = "Bearer 6bfd44fbdcdddc11a88f8274dc38b5c6f0e5121b";
client.Headers[HttpRequestHeader.ContentType] = "application/json";
client.Headers["X-IFORM-API-REQUEST-ENCODING"] = "JSON";
client.Headers["X-IFORM-API-VERSION"] = "1.1";
MyViewModel model = ...
string jsonSerializedModel = JsonConvert.Serialize(model); // <-- Only here you need JSON.NET to serialize your model to a JSON string
byte[] data = Encoding.UTF8.GetBytes(jsonSerializedModel);
byte[] result = client.UploadData(url, data);
// If the API returns JSON here you could deserialize the result
// back to some view model using JSON.NET
}
The UploadData
method will send an HTTP POST request to the remote endpoint. If you want to handle exceptions you could put it in a try/catch
block and catch WebException
which is what this method could throw if for example the remote endpoint returns some non 2xx HTTP response status code.
Here's how you could handle the exception and read the remote server response in this case:
try
{
byte[] result = client.UploadData(url, data);
}
catch (WebException ex)
{
using (var response = ex.Response as HttpWebResponse)
{
if (response != null)
{
HttpStatusCode code = response.StatusCode;
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
string errorContent = reader.ReadToEnd();
}
}
}
}
Notice how in the catch
statement you could determine the exact status code returned by the server as well as the response payload. You could also extract the response headers.