Is there a way to convert this Twilio CURL to RestClient? - c#

I would like to know how to convert this Twilio CURL code to RestClient
I am stuck in the request.AddParamenter() I have not idea how to format it order to pass the Twilio SID,Token, From, To and Body Text Message.
curl -X POST https://api.twilio.com/2010-04-01/Accounts/$TWILIO_ACCOUNT_SID/Messages.json \
-data-urlencode "Body=Hi there" \
-data-urlencode "From=+15017122661" \
-data-urlencode "To=+15558675310" \
-u $TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN
To this:
var client = new RestClient("https://api.twilio.com/2010-04-01/Accounts/$TWILIO_ACCOUNT_SID/Messages.json");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddHeader("cache-control", "no-cache");
request.AddParameter("application/x-www-form-urlencoded", "bodykey=bodyval", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
This is my code now that compile 100% and after I run the code I get a response "Complete" no error message and no entry at twilio dashboard either, it does not send the text message, any idea your help will be much appreciate.
RestClient client = new RestClient("https://api.twilio.com/2010-04-01/Accounts/ACet53f18a4734c339488c1845e619dd9g/Messages.json");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("ACet53f18a4734c339488c1845e619dd9g:daskshdsjkahkashd90ud09as8dasjkhdsa9"));
request.AddHeader("Authorization", "Basic " + base64authorization);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("Body", "Hello World");
request.AddParameter("From", "+15017122661"); //- My Twilio number goes
request.AddParameter("To", "+15017122661");
IRestResponse response = client.Execute(request);
string ResStatus = response.ResponseStatus.ToString(); //- Complete after successfully run.

You can send a RestClient request like this.
RestClient client = new RestClient("https://api.twilio.com/2010-04-01/Accounts/$TWILIO_ACCOUNT_SID/Messages.json");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("$TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN"));
request.AddHeader("Authorization", $"Basic {base64authorization}");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("Body", "Hi");
request.AddParameter("From", "+15017122661");
request.AddParameter("To", "+ 15558675310");
IRestResponse response = client.Execute(request);

Related

Authentication Error while trying to get the DHL Interface to run

I've been trying to get the DHL interface up and running for some time now.
Unfortunately, there is already a lack of authentication.
Request:
client_id == AppID
client_secret = AppToken
var client = new RestClient("https://api.dhlecs.com/auth/v4/accesstoken");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "client_credentials");
request.AddParameter("client_id", client_id);
request.AddParameter("client_secret", client_secret);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
Response:
{"type":"https://api.dhlecs.com/docs/errors/401.0000007", "title":"Invalid
credentials"}
Does anyone have any idea why it doesn't work? Or am I calling something wrong?

RestSharp Post Request Array Object

I've been looking for a way to use RestSharp C# to send POST request with the JSON below.
[{"Guid": "ccda117f-a9b5-4f54-ab4a-07a9cf403ef7"}]
It starts with the bracket and I don't see any reference similar to this.
Can you provide any link or sample code that I can use for reference?
Thanks!
var client2 = new RestClient("https://test.rest.com/api/v2/notifications/channels/" + channelId + "/subscriptions");
var request2 = new RestRequest(Method.POST);
request2.AddHeader("cache-control", "no-cache");
request2.AddHeader("authorization", "Bearer " + access_token);
request2.AddHeader("Content-Type", "application/json");
var myJson = "[{\"Guid\": \"ccda117f-a9b5-4f54-ab4a-07a9cf403ef7\"}]";
request2.AddParameter("application/json", myJson, ParameterType.RequestBody);
IRestResponse response2 = client2.Execute(request2);

Converting restsharp to httpclient

I need to convert this restsharp code to c# HttpClient code.
How would I go about that?
var client = new RestClient("http://localhost:61375/token");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded",
"grant_type=password&username=UserName&password=pa%24%24w0rd",
ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

RestSharp - StatusCode: UnsupportedMediaType

I am trying to post a new customer to a web api. When I execute the following in Fiddler I get no errors:
POST https://api.someurl.com/api/businesses/99999999/contacts HTTP/1.1
User-Agent: Fiddler
Content-Type: application/json
Accept: application/json
Host: api.someurl.com
Authorization: TOKEN json:{"authenticationCode":"kLJBlaUCK0pYY6YXI6qB3CHamq0=","expiryDate":1468083160641,"locale":"en_US","myUserId":88888888888,"restriction":null,"site":"api.someurl.com"}
Content-Length: 931
{"business":9999999999,"collaborationContext":0,"contactInformation":{"campaign":null,"city":"SomeCity","country":"SomeCountry","email":"email#someurl.com","fax":null,"first":"FName","hasShippingAddress":false,"instructions":null,"last":"LName","locale":null,"mobile":null,"name":"FullName","phone":"222.333.4455","postalOrZipCode":"90210","provinceOrState":null,"readOnly":false,"referral":null,"registration":null,"shippingCity":null,"shippingCountry":null,"shippingName":null,"shippingNotes":null,"shippingPhone":null,"shippingPostalOrZipCode":null,"shippingProvinceOrState":null,"shippingStreet1":null,"shippingStreet2":null,"street1":null,"street2":null,"tollFree":null,"url":null},"currency":null,"defaultTaxCode":null,"id":0,"incomeOrExpenseAccount":null,"linkedBusiness":null,"payableAccount":null,"paymentAccount":null,"paymentTerms":null,"prefix":null,"receivableAccount":null,"removed":false,"type":"CUSTOMER"}
When I try to execute (what I think is) the equivalent (see below), I get "StatusCode: UnsupportedMediaType, Content-Type: text/xml, Content-Length: 0)"
private static string PostContact(string busId, Contact contact )
{
var restClient = new RestClient("https://api.someurl.com");
var jsonToken = GetJsonToken();
// var contactJson = JsonConvert.SerializeObject(contact);
var req = new RestRequest("/api/businesses/{business-id}/contacts");
req.Method = Method.POST;
req.Parameters.Clear();
req.AddHeader("Content-Type", "application/json");
req.AddHeader("Accept", "application/json");
req.AddUrlSegment("business-id", busId);
req.AddParameter("Authorization", string.Format("TOKEN json:{0}", jsonToken), ParameterType.HttpHeader);
req.AddParameter("application/json", contact, ParameterType.RequestBody);
var resp = restClient.Execute(req);
Console.WriteLine(resp.StatusCode);
return resp.Content;
}
Is there a special order to adding parameters or headers, or am I missing something?
Resolved!
var client = new RestClient(url);
var request = new RestRequest(Method.POST);
request.AddHeader("Cache-Control", "no-cache");
///request.AddHeader("Authorization", "Bearer " + access_token);
request.AddHeader("Authorization", token);
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("undefined", JsonRequest, ParameterType.RequestBody);
var response = client.Execute(request);
var responseJson = response.Content;
I have another easier solution:
Add this single line (if NO file is attached)
req.AlwaysMultipartFormData = true;
In my case a piece of source code look like this:
var client2 = new RestClient("https://myurl.com/api/site/Create");
client2.Options.MaxTimeout = -1;`
var request2 = new RestRequest("https://myurl.com/api/site/Create", Method.Post);
request2.AddHeader("Authorization", "Bearer "+ _authstr);
// AddFile below, therefore commented out
// request2.AlwaysMultipartFormData = true;
request2.AddParameter("PFolderId", "a1c1w000000GR5hAAG");
request2.AddParameter("Title", "MyTitle5");
request2.AddParameter("GeoRegion", "{E|BE|BRUXELLES-BRUSSEL}");
request2.AddParameter("SeismicZone", "0");
request2.AddFile("file", "C:/Users/abc/Desktop/Drawing.png");
RestResponse response2 = client.Execute(request2);

Converting HttpClient to RestSharp

I have Httpclient functions that I am trying to convert to RestSharp but I am facing a problem I can't solve with using google.
client.BaseAddress = new Uri("http://place.holder.nl/");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",access_token);
HttpResponseMessage response = await client.GetAsync("api/personeel/myID");
string resultJson = response.Content.ReadAsStringAsync().Result;
This Code is in my HttpClient code, which works good, but I can't get it to work in RestSharp, I always get Unauthorized when using RestSharp like this:
RestClient client = new RestClient("http://place.holder.nl");
RestRequest request = new RestRequest();
client.Authenticator = new HttpBasicAuthenticator("Bearer", access_token);
request.AddHeader("Accept", "application/json");
request.Resource = "api/personeel/myID";
request.RequestFormat = DataFormat.Json;
var response = client.Execute(request);
Am I missing something with authenticating?
This has fixed my problem:
RestClient client = new RestClient("http://place.holder.nl");
RestRequest request = new RestRequest("api/personeel/myID", Method.GET);
request.AddParameter("Authorization",
string.Format("Bearer " + access_token),
ParameterType.HttpHeader);
var response = client.Execute(request);
Upon sniffing with Fiddler, i came to the conclusion that RestSharp sends the access_token as Basic, so with a plain Parameter instead of a HttpBasicAuthenticator i could force the token with a Bearer prefix
Try this
RestClient client = new RestClient("http://place.holder.nl");
RestRequest request = new RestRequest("api/personeel/myID",Method.Get);
request.AddParameter("Authorization",$"Bearer {access_token}",ParameterType.HttpHeader);
request.AddHeader("Accept", "application/json");
request.RequestFormat = DataFormat.Json;
var response = client.Execute(request);
If anyone happens on this, it looks like as of V 106.6.10 you can simply add default parameters to the client to save yourself from having to add your Auth token to every request method:
private void InitializeClient()
{
_client = new RestClient(BASE_URL);
_client.DefaultParameters.Add(new Parameter("Authorization",
string.Format("Bearer " + TOKEN),
ParameterType.HttpHeader));
}

Categories