How to download and Upload data to any REST Service (Synchronous)
Here i would like to show, how you can download and upload the Data to REST Services either provided by Third party or to your own REST Service.
We will be looking into the Synchronous way of downloading and uploading the data.
Here i will be showing the Synchronous methods for downloading and uploading data
.Net WebClient has the handy methods for Upload and download different types of data like String, Byte Data or File WebClient Download Methods
client.DownloadString()
client.DownloadData()
client.DownloadFile() WebClient Upload Methods
client.UploadString();
client.UploadData();
client.UploadFile();
By using the below code you can create the REST Client application which will be handy for consuming any REST Services API.
The below snippet can be used for any WEB Service with some modification.
Code Snippet. Take below code and create class library.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Xml.Linq;
namespace RestServiceClient
{
///
/// REST Client to GET or POST the data
///
public class RestClient
{
private string responseData = String.Empty;
//private string url = String.Empty;
public string Url { get; set; }
public string Data { get; set; }
private WebClient client;
///
/// Download Data from REST Service in Synchronous way.
///
///
///
public String GetDataSync(string url)
{
using (client = new WebClient())
{
responseData = GetXmlData(client.DownloadString(new Uri(url)));
}
return responseData;
}
///
/// Upload/Post Data using REST Service in Synchronous way.
///
///
///
///
public String PostDataSync(string url, string data)
{
using (client = new WebClient())
{
responseData = GetXmlData(client.UploadString(new Uri(url), data));
}
return responseData;
}
private String GetXmlData(String xml)
{
XElement doc = XElement.Parse(xml);
return doc.ToString();
}
}
}
We can call above methods in Console or Windows application like shown below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Management.Instrumentation;
using System.Management;
using System.Threading;
using RestServiceClient;
namespace RestClientApplication
{
class Program
{
public static void Main(string[] args) {
RestClient client = new RestClient();
string url = "http://www.thomas-bayer.com/sqlrest/CUSTOMER/";
Console.WriteLine(client.GetDataSync(url));
Console.Read();
}
}
}