9

I need to submit data via POST request to a third party api, I have the url to submit to, but I am trying to avoid first sending the data to the client-side and then posting it again from there. Is there a way to POST information from codebehind directly?

Any ideas are appreciated.

RealityDysfunction
  • 2,609
  • 3
  • 26
  • 53
  • Check out this related article... http://stackoverflow.com/questions/4088625/net-simplest-way-to-send-post-with-data-and-read-response – xspydr Jan 10 '14 at 18:32

3 Answers3

11

From the server side you can post it to the url.

See the sample code from previous stackoverflow question - HTTP request with post

using (var wb = new WebClient()) 
{
         var data = new NameValueCollection();
         data["username"] = "myUser";
         data["password"] = "myPassword";


         var response = wb.UploadValues(url, "POST", data); 
}

Use the WebRequest class to post.

http://msdn.microsoft.com/en-us/library/debx8sh9(v=vs.110).aspx

Alternatively you can also use HttpClient class:

http://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.110).aspx

Hope this helps. Please post if you are facing issues.

Community
  • 1
  • 1
George Philip
  • 704
  • 6
  • 21
9

Something like this?

string URI = "http://www.myurl.com/post.php";
string myParameters = "param1=value1&param2=value2&param3=value3";

using (WebClient wc = new WebClient())
{
    wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
    string HtmlResult = wc.UploadString(URI, myParameters);
}

How to post data to specific URL using WebClient in C#

Community
  • 1
  • 1
crthompson
  • 15,653
  • 6
  • 58
  • 80
2

You should to use WebRequest class:

var request = (HttpWebRequest)WebRequest.Create(requestedUrl);
request.Method = 'POST';
using (var resp = (HttpWebResponse)request.GetResponse()) {
    // your logic...
}

Full info is here https://msdn.microsoft.com/en-us/library/debx8sh9(v=vs.110).aspx

NoWar
  • 36,338
  • 80
  • 323
  • 498
alexmac
  • 19,087
  • 7
  • 58
  • 69