Request Parameter Format Requirements
The format of request parameters must match the ContentType header:
- For ContentType "application/x-www-form-urlenocded" (form data), parameters should be in format: key1=value1&key2=value2
- For ContentType "application/json" (JSON data), parameters should be in JSON format: {"key1":"value1","key2":"value2"}
Custom headers can be added using the Headers.Add(key, value) method and retrieved using Headers.Get(key).
HTTP GET Implementation
public static string ExecuteHttpGet(string url)
{
string responseContent = string.Empty;
try
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "GET";
using HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
using Stream responseStream = webResponse.GetResponseStream();
using StreamReader streamReader = new StreamReader(responseStream);
responseContent = streamReader.ReadToEnd();
}
catch (Exception error)
{
// Handle exception
}
return responseContent;
}
HTTP POST Implementation
public static string ExecuteHttpPost(string url, string requestData,
Dictionary<string, string> customHeaders = null)
{
string responseContent = string.Empty;
try
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = Encoding.UTF8.GetByteCount(requestData);
if (customHeaders != null && customHeaders.Count > 0)
{
foreach (var header in customHeaders)
{
webRequest.Headers.Add(header.Key, header.Value);
}
}
using Stream requestStream = webRequest.GetRequestStream();
using StreamWriter streamWriter = new StreamWriter(requestStream);
streamWriter.Write(requestData);
using HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
using Stream responseStream = webResponse.GetResponseStream();
using StreamReader streamReader = new StreamReader(responseStream);
responseContent = streamReader.ReadToEnd();
}
catch (Exception error)
{
// Handle exception
}
return responseContent;
}
File Upload Implementation
public static string UploadFile(string url, string fileDescription,
string filePath, string fileName, string apiKeyHeader = "X-API-Key",
string apiKeyValue = "sample-api-key")
{
string result = string.Empty;
try
{
Encoding encoding = Encoding.UTF8;
string boundary = $"----{Guid.NewGuid()}";
string startBoundary = $"--{boundary}";
string endBoundary = $"--{boundary}--";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = $"multipart/form-data; boundary={boundary}";
request.Method = "POST";
request.Headers.Add(apiKeyHeader, apiKeyValue);
StringBuilder bodyBuilder = new StringBuilder();
bodyBuilder.AppendLine(startBoundary);
bodyBuilder.AppendLine("Content-Disposition: form-data; name=\"attachment\"");
bodyBuilder.AppendLine();
bodyBuilder.AppendLine(fileDescription);
bodyBuilder.AppendLine(startBoundary);
bodyBuilder.AppendLine($"Content-Disposition: form-data; name=\"file\"; filename=\"{fileName}\"");
bodyBuilder.AppendLine("Content-Type: application/octet-stream");
bodyBuilder.AppendLine();
byte[] headerBytes = encoding.GetBytes(bodyBuilder.ToString());
byte[] fileBytes = ReadFileBytes(filePath);
byte[] footerBytes = encoding.GetBytes($"\r\n{endBoundary}");
byte[] requestBody = new byte[headerBytes.Length + fileBytes.Length + footerBytes.Length];
Array.Copy(headerBytes, 0, requestBody, 0, headerBytes.Length);
Array.Copy(fileBytes, 0, requestBody, headerBytes.Length, fileBytes.Length);
Array.Copy(footerBytes, 0, requestBody, headerBytes.Length + fileBytes.Length, footerBytes.Length);
request.ContentLength = requestBody.Length;
using Stream requestStream = request.GetRequestStream();
requestStream.Write(requestBody, 0, requestBody.Length);
using HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using Stream responseStream = response.GetResponseStream();
using StreamReader reader = new StreamReader(responseStream, encoding);
result = reader.ReadToEnd();
}
catch (Exception error)
{
// Handle exception
}
return result;
}
private static byte[] ReadFileBytes(string filePath)
{
byte[] fileData;
using FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
fileData = new byte[fileStream.Length];
fileStream.Read(fileData, 0, fileData.Length);
return fileData;
}
Async File Upload with HttpClient
public static async Task<string> UploadFileAsync(string url, string fileDescription,
string filePath, string fileName, string apiKeyHeader = "X-API-Key",
string apiKeyValue = "sample-api-key")
{
string result = string.Empty;
try
{
using HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.Timeout = TimeSpan.FromMinutes(20);
using FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
MultipartFormDataContent formData = new MultipartFormDataContent();
formData.Add(new StringContent(fileDescription), "attachment");
formData.Add(new StreamContent(fileStream, (int)fileStream.Length), "file", fileName);
HttpResponseMessage response = await httpClient.PostAsync(url, formData);
if (response.StatusCode == HttpStatusCode.OK)
{
result = await response.Content.ReadAsStringAsync();
}
}
catch (Exception error)
{
// Handle exception
}
return result;
}</string>
Form Data POST with HttpClient
public static async Task<string> PostFormDataAsync(string url,
Dictionary<string, string> headers, Dictionary<string, string> formData)
{
string result = string.Empty;
using HttpClient client = new HttpClient();
if (headers != null && headers.Count > 0)
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
MultipartFormDataContent formContent = new MultipartFormDataContent();
foreach (var field in formData)
{
formContent.Add(new StringContent(field.Value), field.Key);
}
HttpResponseMessage response = await client.PostAsync(url, formContent);
if (response.StatusCode == HttpStatusCode.OK)
{
result = await response.Content.ReadAsStringAsync();
}
return result;
}</string>