How to create HTTP post request - c#

Hello I'm new at programing so my question might be a little bit odd. My boss ask me to create a HTTP post request using a key and a message to access our client.
I already seen the article Handle HTTP request in C# Console application but it doesn't include where I put the key and message so the client API knows its me. Appreciate the help in advance.

I believe you wanted this:
HttpWebRequest httpWReq =
(HttpWebRequest)WebRequest.Create("http://domain.com/page.aspx");
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "username=user";
postData += "&password=pass";
byte[] data = encoding.GetBytes(postData);
httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
httpWReq.ContentLength = data.Length;
using (Stream stream = httpWReq.GetRequestStream())
{
stream.Write(data,0,data.Length);
}
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

You could use a WebClient:
using (var client = new WebClient())
{
// Append some custom header
client.Headers[HttpRequestHeader.Authorization] = "Bearer some_key";
string message = "some message to send";
byte[] data = Encoding.UTF8.GetBytes(message);
byte[] result = client.UploadData(data);
}
Of course depending on how the API expects the data to be sent and which headers it requires you will have to adapt this code to match the requirements.

Related

C# Post JSON with Authentication Header

I have problem with post JSON with authentication/Authorization.. Below is my code.. opponent said that they didnt receive the header...and i have no idea why...
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(stringData);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(serverURL);
req.Method = "POST";
req.ContentType = "application/json";
req.ContentLength = data.Length;
req.Headers.Add("Authentication", merchantID);
req.Headers["Authentication"] = merchantID;
Stream newStream = req.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
string returnString = response.StatusCode.ToString();
i am writing some example code to attach header while you calling service...
hope it is needful...
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(stringData);
HttpWebRequest reqest = (HttpWebRequest)WebRequest.Create(serviceUri);
reqest.Headers.Add(LoginName,LoginName);
reqest.Headers.Add(AuthenticationKey,AuthenticationKey);
reqest.Headers.Add(SessionKey,SessionKey);
reqest.ContentType = "application/json";
Stream newStream = req.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
string returnString = response.StatusCode.ToString();
I cannot surely say where the problem is. It can be even on a server-side.
Recently I worked on a project with header authentication and I have noticed an interesting thing. My PHP server received these headers with 'HTTP_' prefix.
In other words, I was making a request like:
req.Headers.Add("Authentication", merchantID);
And received it on server this way:
echo $_SERVER['HTTP_Authentication'];
I have spent a bunch of time to find it out.
You, actually, can ask your opponent if any similar header is present or ask him to examine your requests better and give you a feedback.
Also, try using WebClient. Maybe, it will help.
Furthermore, it is much more convenient.
string data = "{\"a\": \"b\"}";
WebClient client = new WebClient();
client.Headers.Add("Content-Type", "application/json");
client.Headers.Add("Authentication", merchantID);
var result = client.UploadString(serverURL, "POST", data);

Rest API returns 401 unauthorized exception when trying to POST to it

Here is the method. I have been working on this for quite a while, and modifying the header values and such. It still comes up with 401 Unauthorized Exception unless I include content-length header and then it will come up with another error saying the content-length header is invalid. Does anyone have any idea how to resolve this?
I have also tried doing this through an HTTPWebRequest.
Webclient Code:
public void postResponse(string supplierid, string token, string geturl, string lineid)
{
lineid = lineid.Trim();
//string postdata = ("{'supplier_id':'"+supplierid+"', 'token':'"+token+"','ci_lineitem_ids':["+lineid+"]}");
try
{
string postdata = ("{'supplier_id':'"+supplierid+"','token':'"+token+"','ci_lineitem_ids':["+lineid+"]}");
Console.WriteLine(postdata);
WebClient postWithParamsClient = new WebClient();
postWithParamsClient.UploadStringCompleted +=
new UploadStringCompletedEventHandler(postWithParamsClient_UploadStringCompleted);
postWithParamsClient.UseDefaultCredentials = true;
postWithParamsClient.Credentials = new NetworkCredential(supplierid, token);
postWithParamsClient.Headers.Add("Content-Type", "application/json");
string headerlength = postdata.Length.ToString();
//postWithParamsClient.Headers["Content-Length"] = headerlength;
postWithParamsClient.UploadStringAsync(new Uri(geturl),
"POST",
postdata);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
HTTPWebRequest
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] postBytes = encoding.GetBytes(postdata);
// used to build entire input
StringBuilder sb = new StringBuilder();
// used on each read operation
byte[] buf = new byte[8192];
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(geturl);
request.Credentials = new NetworkCredential(supplierid, token);
request.Method = "POST";
request.ContentLength = postBytes.Length;
request.ContentType = "application/json";
Stream postStream = request.GetRequestStream();
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Close();
You should try to use fiddler to see what you send and compare to what you server need. Check authorization header and the validity of your credentials. I think it's the first thing to do

Creating CURL Request ASP.NET

curl -X POST 'https://api.twilio.com/2010-04-01/Accounts/AC053acaaf55d75ef32233132196e/Messages.json' \
--data-urlencode 'To=5555555555' \
--data-urlencode 'From=+15555555555' \
--data-urlencode 'Body=Test' \
-u AC053acaaf55d75a393498192382196e:[AuthToken]
I have the above curl code for an API I need to connect to. The problem is I need to connect using ASP.NET (C#). I'm not very familiar with ASP.NET and don't really know where to begin. I know how to code this in PHP but ASP.NET is another matter. From the research I've done I need to use WebRequest. How do I feed in the post data and the authtoken (-u AC053acaaf55d75a393498192382196e:[AuthToken]) part of the request.
string url = "https://api.twilio.com/2010-04-01/Accounts/AC053acaaf55d75ef32233132196e/Messages.json";
WebRequest myReq = WebRequest.Create(url);
myReq.Method = "POST";
Twilio evangelist here.
Just to make sure we are on the same page, you need to make a POST request to theMessages endpoint in the Twilio API, but you cannot use our helper library.
Not a problem, you can just use .NETs native HTTP client libraries, HttpWebRequest and HttpWebResponse. Thats going to look something like this:
//Twilio Credentials
string accountsid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
string authtoken = "asdsadasdasdasdasdsadsaads";
//Twilio API url, putting your AccountSid in the URL
string urltemplate = "https://api.twilio.com/2010-04-01/Accounts/{0}/Messages.json";
string url = string.Format(urltemplate, accountsid);
//Create a basic authorization
string basicauthtoken = string.Format("Basic {0}", System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(accountsid + ":" + authtoken)));
//Build and format the HTTP POST data
string formencodeddata = "To=+15555555555&From=+15556666666&Body=Hello World";
byte[] formbytes = System.Text.ASCIIEncoding.Default.GetBytes(formencodeddata);
//Create a new HTTP request object, set the method to POST and write the POST data to it
var webrequest = (HttpWebRequest)WebRequest.CreateHttp(url);
webrequest.Method = "POST";
webrequest.ContentType = "application/x-www-form-urlencoded";
webrequest.Headers.Add("Authorization", basicauthtoken);
using (Stream postStream = webrequest.GetRequestStream()) {
postStream.Write(formbytes, 0, formbytes.Length);
}
//Make the request, get a response and pull the data out of the response stream
var webresponse = (HttpWebResponse)webrequest.GetResponse();
Stream responseStream = webresponse.GetResponseStream();
var reader = new StreamReader(responseStream);
string result = reader.ReadToEnd();
There are also async versions of the GetRequestStream and GetResponse methods if you need them.
Hope that helps.
Twilio has some great docs for this here: http://www.twilio.com/docs/api/rest/making-calls
they also have a great c# library here; twilio.com/docs/csharp/install but here's an example in C# showing how to make a call.
using System;
using Twilio;
class Example {
static void Main(string[] args) {
// Find your Account Sid and Auth Token at twilio.com/user/account
string AccountSid = "AC3094732a3c49700934481addd5ce1659";
string AuthToken = "{{ auth_token }}";
var twilio = new TwilioRestClient(AccountSid, AuthToken);
var options = new CallOptions();
options.Url = "http://demo.twilio.com/docs/voice.xml";
options.To = "+14155551212";
options.From = "+14158675309";
var call = twilio.InitiateOutboundCall(options);
Console.WriteLine(call.Sid);
}
}
Working code for me
string accountsid = "AccountSid";
string authtoken = "AuthToken";
//Twilio API url, putting your AccountSid in the URL
string urltemplate = "https://api.twilio.com/2010-04-01/Accounts/{0}/Messages.json";
string url = string.Format(urltemplate, accountsid);
//Get Client Secret and client key from the API Keys section-- https://www.twilio.com/docs/iam/keys/api
string basicauthtoken = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("ClientSecret:ClientKey"));
//Build and format the HTTP POST data
string formencodeddata = "To={To}&From={From}&Body={Body}";
byte[] formbytes = System.Text.ASCIIEncoding.Default.GetBytes(formencodeddata);
//Create a new HTTP request object, set the method to POST and write the POST data to it
var webrequest = (HttpWebRequest)WebRequest.CreateHttp(url);
webrequest.Method = "POST";
webrequest.ContentType = "application/x-www-form-urlencoded";
webrequest.Headers.Add("Authorization", basicauthtoken);
using (Stream postStream = webrequest.GetRequestStream())
{
postStream.Write(formbytes, 0, formbytes.Length);
}
//Make the request, get a response and pull the data out of the response stream
var webresponse = (HttpWebResponse)webrequest.GetResponse();
Stream responseStream = webresponse.GetResponseStream();
var reader = new StreamReader(responseStream);
string result = reader.ReadToEnd();

C# code to passing json data with WebService

response = requests.patch( "https://<manageraddress>/api/admin/configuration/v1/conference/1/", auth=('<user1>', '<password1>'), verify=False, data=json.dumps({'pin': '1234'}) https://tsmgr.tsecurevideo.com/api/admin/configuration/v1/conference/1/"
I have tried
HttpWebRequest httpWReq =(HttpWebRequest)WebRequest.Create(string.Format("https://tsmgr.tsecurevideo.com/api/admin/configuration/v1/conference/2/"));
Encoding encoding = new UTF8Encoding();
string postData = "{\"pin\":\"1234\"}";
byte[] data = encoding.GetBytes(postData);
httpWReq.ProtocolVersion = HttpVersion.Version11;
httpWReq.Method = "POST";
httpWReq.ContentType = "application/json";//charset=UTF-8";
string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("admin" + ":" + "password"));
httpWReq.Headers.Add("Authorization", "Basic " + credentials);
httpWReq.ContentLength = data.Length;
Stream stream = httpWReq.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
string s = response.ToString();
StreamReader reader = new StreamReader(response.GetResponseStream());
I am getting the error
The remote server returned an error: (501) Not Implemented.
try to send credentials in this way
string auth = string.Format("{0}:{1}", "admin","password");
string data = Convert.ToBase64String(Encoding.ASCII.GetBytes(auth));
string credentials= string.Format("{0} {1}", "Basic", data );
httpWReq.Headers[HttpRequestHeader.Authorization] = credentials;
refer here for documentation in Encoding.ASCII
From the HTTP spec:
501 Not Implemented
The server does not support the functionality required to fulfill the request. This is the appropriate response when the server does not recognize the request method and is not capable of supporting it for any resource.
Sounds like the server doesn't support the PATCH method.

Sending a string to a PHP page and having the PHP Page Display The String

What I'm trying to do is have my PHP page display a string that I've created through a function in my C# application, via System.Net.WebClient.
That's really it. In it' s simplest form, I have:
WebClient client = new WebClient();
string URL = "http://wwww.blah.com/page.php";
string TestData = "wooooo! test!!";
byte[] SendData = client.UploadString(URL, "POST", TestData);
So, I'm not even sure if that's the right way to do it.. and I'm not sure how to actually OBTAIN that string and display it on the PHP page. something like print_r(SendData) ??
ANY help would be greatly appreciated!
There are two halves to posting. 1) The code that posts to a page and 2) the page that receives it.
For 1)
Your C# looks ok. I personally would use:
string url = "http://wwww.blah.com/page.php";
string data = "wooooo! test!!";
using(WebClient client = new WebClient()) {
client.UploadString(url, data);
}
For 2)
In your PHP page:
if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
{
$postData = file_get_contents('php://input');
print $postData;
}
Read about reading post data in PHP here:
http://us.php.net/manual/en/wrappers.php.php
http://php.net/manual/en/reserved.variables.httprawpostdata.php
Use This Codes To Send String From C# With Post Method
try
{
string url = "";
string str = "test";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
string Data = "message="+str;
byte[] postBytes = Encoding.ASCII.GetBytes(Data);
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream resStream = response.GetResponseStream();
var sr = new StreamReader(response.GetResponseStream());
string responseText = sr.ReadToEnd();
}
catch (WebException)
{
MessageBox.Show("Please Check Your Internet Connection");
}
and php page
<?php
if (isset($_POST['message']))
{
$msg = $_POST['message'];
echo $msg;
}
?>

Categories