Friday, January 22, 2010

HTTP POST Requests

static string HttpPost(string url,
string[] paramName, string[] paramVal)
{
HttpWebRequest req = WebRequest.Create(new Uri(url))
as HttpWebRequest;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";

// Build a string with all the params, properly encoded.
// We assume that the arrays paramName and paramVal are
// of equal length:
StringBuilder params = new StringBuilder();
for (int i = 0; i < paramName.Length; i++) {
params.append(paramName[i]);
params.append("=");
params.append(HttpUtility.UrlEncode(paramVal[i]));
params.append("&");
}

// Encode the parameters as form data:
byte[] formData =
UTF8Encoding.UTF8.GetBytes(params.toString());
req.contentLength = formData.Length;

// Send the request:
using (Stream post = req.GetRequestStream())
{
post.Write(formData, 0, formData.Length);
}

// Pick up the response:
string result = null;
using (HttpWebResponse resp = req.GetResponse()
as HttpWebResponse)
{
StreamReader reader =
new StreamReader(resp.GetResponseStream());
result = reader.ReadToEnd();
}

return result;
}

0 comments:

Post a Comment