Simple And Generic Web Service Proxy Using HttpWebRequest/HttpWebResponse objects
The below class is a simple layer that can be used to access web service methods, it's depend on three tricks (1)initializing HttpWebRequest object, (2)encoding and passing request data that represent web method input parameters and (3)get response from web method.
The class WSProxy only have two methods the first one is [CallWebMethod] that can call any web method with any number of paramters depend on it's input parameter the dictionary object that preserve method parameters in form of key/value, the second method is [CreateHttpRequestData] that is responsible about encoding request data (parameters with it's values) to send it with request.
public class WSProxy
{
public string CallWebMethod(string webServiceURL, string webMethod, Dictionary<string, string> dicParameters)
{
try
{
byte[] _requestData = this.CreateHttpRequestData(dicParameters);
string uri = webServiceURL + "/" + webMethod;
HttpWebRequest _httpRequest = (HttpWebRequest)HttpWebRequest.Create(uri);
_httpRequest.Method = "POST";
_httpRequest.KeepAlive = false;
_httpRequest.ContentType = "application/x-www-form-urlencoded";
_httpRequest.ContentLength = _requestData.Length;
_httpRequest.Timeout = 30000;
HttpWebResponse _httpResponse = null;
string _response = string.Empty;
_httpRequest.GetRequestStream().Write(_requestData, 0, _requestData.Length);
_httpResponse = (HttpWebResponse)_httpRequest.GetResponse();
System.IO.Stream _baseStream = _httpResponse.GetResponseStream();
System.IO.StreamReader _responseStreamReader = new System.IO.StreamReader(_baseStream);
_response = _responseStreamReader.ReadToEnd();
_responseStreamReader.Close();
return _response;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private byte[] CreateHttpRequestData(Dictionary<string, string> dic)
{
StringBuilder _sbParameters = new StringBuilder();
foreach (string param in dic.Keys)
{
_sbParameters.Append(param);//key => parameter name
_sbParameters.Append('=');
_sbParameters.Append(dic[param]);//key value
_sbParameters.Append('&');
}
_sbParameters.Remove(_sbParameters.Length - 1, 1);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(_sbParameters.ToString());
}
}
You can download this demo application that demonstrate WSProxy Class functionality