7

I have to integrate with a third party API. To use the service, I have to "POST" to a specific url with certain parameters.

The example code provided by the service is in php and is as follows

$data = array('From' => '0999999', 'To' => '08888888'); 
$curl = curl_init();
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);  <--- Ignore SSL warnings
curl_setopt($curl, CURLOPT_POST, true); 
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

I am trying to use the WebRequest class to achieve the same in .net. However, I am a bit confused about how to set the post parameter data. I figured $data above is nothing but a Dictionary. So I created a equivalent dictionary. However, how do I set the post parameters with the dictionary values?

In http://msdn.microsoft.com/en-us/library/debx8sh9.aspx, they have serialized a string to a byte array and then set is as the post parameter in the dataStream. How do I do the same for a Dictionary?

Or is my approach incorrect? Is there a better way to do this?

shashi
  • 4,616
  • 9
  • 50
  • 77

4 Answers4

9

Generally, WebClient.UploadValues is going to be the easiest approach here; see MSDN for a full example. Note, however, that this only covers CURLOPT_POSTFIELDS and CURLOPT_POST. Fail on error is automatic and implicit, and the response is already included as a byte[].

i.e.

using(var client = new WebClient()) {
    var data = new NameValueCollection();
    data.Add("From", "0999999");
    data.Add("To", "08888888");
    var result = client.UploadValues(url, data);
}

note POST is implicit here; if you need a different http method, use the overload:

var result = client.UploadValues(url, "PUT", data); // for example
Ben
  • 54,723
  • 49
  • 178
  • 224
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Is there an equivalent of CURLOPT_SSL_VERIFYPEER such that I can ignore any SSL exceptions? The remote certificate is self generated SSL certificate and the third party Api developers want others to ignore any SSL warnings. Or is the approach shown at http://www.ben-morris.com/asp-net-web-services-and-ssl-certificates-establishing-a-trust-relationship the easiest way? Should this be a separate question? – shashi Oct 09 '11 at 21:05
  • 1
    @sassyboy re SSL, see http://stackoverflow.com/questions/109186/bypass-invalid-ssl-certificate-errors-when-calling-web-services-in-net/865786#865786 – Marc Gravell Oct 09 '11 at 21:42
4

If you are using url encoded post data you can url encode each key/value pair of your dictionary using HttpServerUtility.UrlEncode Method (String)

// Build postData
StringBuilder post = new StringBuilder();
foreach(item in dictionary) {
  post.AppendFormat("&{0}={1}", item.key, HttpUtility.UrlEncode(item.value));
}
string postData = post.ToString();

// HTTP POST
Uri uri = new Uri(url);
request = (HttpWebRequest) WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
using(Stream writeStream = request.GetRequestStream())
{
  UTF8Encoding encoding = new UTF8Encoding();
  byte[] bytes = encoding.GetBytes(postData);
  writeStream.Write(bytes, 0, bytes.Length);
}
Amen Jlili
  • 1,884
  • 4
  • 28
  • 51
Aaron Anodide
  • 16,906
  • 15
  • 62
  • 121
1

Just in case you have to use HttpWebRequest, the code below converts a Dictionary<String,String> named formVars to a byte[] named toPost:

byte[] toPost = System.Text.Encoding.UTF8.GetBytes(
    String.Join("&", formVars.Select(x =>
        HttpUtility.UrlEncode(x.Key) + "=" +
        HttpUtility.UrlEncode(x.Value)));
);

Play with a working copy at https://dotnetfiddle.net/IOzIE6

LinuxDisciple
  • 2,289
  • 16
  • 19
0

You probably want to use the

http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://url");
request.AllowWriteStreamBuffering = true;
request.Method = "POST";
string post = "From=0999999&To=08888888";
request.ContentLength = post.Length;
request.ContentType = "application/x-www-form-urlencoded";

StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(post);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
jmoreno
  • 12,752
  • 4
  • 60
  • 91