Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submit POST request from codebehind in ASP.NET [duplicate]

Tags:

c#

post

asp.net

api

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.

like image 412
RealityDysfunction Avatar asked Jan 10 '14 18:01

RealityDysfunction


3 Answers

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#

like image 189
crthompson Avatar answered Oct 16 '22 10:10

crthompson


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.

like image 10
George Philip Avatar answered Oct 16 '22 09:10

George Philip


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

like image 2
alexmac Avatar answered Oct 16 '22 08:10

alexmac