How to download and Upload data to any REST Service (Asynchronous)


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 Asynchronous 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.DownloadStringAsync()
client.DownloadDataAsync()
client.DownloadFileAsync()

WebClient Upload Methods




client.UploadStringAsync();
client.UploadDataAsync();
client.UploadFileAsync();

Code Snippet



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 by providing URL in Asynchronous way.
///

///
public void GetDataAsync(Action callback)
{
using ( client = new WebClient()){
client.DownloadStringCompleted += (s,e) => callback(e.Error==null ? GetXmlData(e.Result) : e.Error.Message);
client.DownloadStringAsync(new Uri(Url));
};

}
///
/// Upload/Post Data using REST Service in Asynchhronos Way.
///

///
public void PostDataAsync(Action callback)
{
using (client = new WebClient())
{

client.UploadStringCompleted += (s, e) => callback(e.Error == null ? GetXmlData(e.Result) : e.Error.Message);
client.UploadStringAsync(new Uri(Url), "POST", Data);

}
}
private String GetXmlData(String xml)
{
XElement doc = XElement.Parse(xml);
return doc.ToString();
}
}
}




Call above code in Windows Form Application



private void btnGET_Click(object sender, EventArgs e)
{
String url = txtURL.Text;
//http://www.thomas-bayer.com/sqlrest/CUSTOMER/
RestServiceClient.RestClient serviceClient = new RestServiceClient.RestClient();
serviceClient.Url = @"http://www.thomas-bayer.com/sqlrest/CUSTOMER/";
serviceClient.GetDataAsync(data => txtResponse.Text = data);
}



Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: