Friday, October 28, 2005

Using Web Response

You can the HTTP WebRequest and WebResponse objects to contact a remote server through your code, send POST data and handle a response.

Below is a method to support this activity. The example code uses a payment gateway service, sending it POST data for a payment transaction and retrieving the response.

private object ProcessHTTPRequest(IPaymentProvider provider, string POSTdata)
{
ASCIIEncoding encoding=new ASCIIEncoding();
POSTdata = "VPSProtocol=2.2&TxType=PREAUTH&Vendor=MyVendor&VendorTxCode=55555&Amount=444&Currency=GBP&Description=TestDesc";
POSTdata += "&CardHolder=Test&CardNumber=000000000000&StartDate=0105&ExpiryDate=1205&IssueNumber&CV2&CardType=Visa&BillingAddress=sdklfjsdf&BillingPostCode=cmdmdm";
byte[] data = encoding.GetBytes(POSTdata);


// Create a new HTTP Web Request.
HttpWebRequest request;


try
{
System.Uri uri = new System.Uri(provider.AbsoluteUrl);
request = (HttpWebRequest)WebRequest.CreateDefault(uri);

}
catch (WebException exRequest)
{
throw exRequest;
}

// Set properties of the request object.
request.Method = "POST";
request.ContentType="application/x-www-form-urlencoded";
request.ContentLength = data.Length;

// *** WRITE THE POST DATA *** //
try
{
Stream newStream = request.GetRequestStream();
// Send the data.
newStream.Write(data, 0, data.Length);
newStream.Close();
}
catch
{}


// Create a new WebResponse object.
WebResponse response;

try
{
response = request.GetResponse();
}
catch (WebException exResponse)
{
throw exResponse;
}

string serverResponse = ""; // String for response output.

try
{
// *** READ *** //
// Get the response.
Stream responseStream = response.GetResponseStream();
// Create a stream reader from the returned stream.
StreamReader sr = new StreamReader(responseStream);
// Read the response.
serverResponse = sr.ReadToEnd();
}
catch (WebException exRead)
{
throw exRead;
}
catch (Exception genException2)
{
throw genException2;
}

// Return the response.
return serverResponse;

}

No comments:

Fixes to common .NET problems, as well as information on .NET features and solutions to common problems that are not language-specific.

Fixes to common .NET problems, as well as information on .NET features and solutions to common problems that are not language-specific.

Z