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);
Related
I code C#. In my C# code add parameter "aliasID" and send request without "aliasID".
But when I use Postman, I add "aliasID" and it was sent.
Code
namespace TrainEyeQTech.ViewModel
{
internal static class SetupAPI
{
public static void Register()
{
RestClient client = new RestClient("faceid/api/domain/register");
//client.Timeout = -1;
var request = new RestRequest("", Method.Post);
request.AddHeader("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiaW50ZXJuYWwtcmVnaXN0ZXIiLCJzZXJ2aWNlIjoiZmFjZWlkLXJlZ2lzdGVyIiwiZXh0cmEiOiJpbnRlcm5hbC1kZXYiLCJpYXQiOjE2MzUwODgzMjAsImV4cCI6MTY2NjYyNDMyMH0.8CBqXQNuCYXBjK7Nt4_fw1rZPIgK6WdZRbhIvWyaS1s");
request.AddHeader("Content-Type", "multipart/form-data; boundary=<calculated when request is sent>");
request.AddHeader("Cookie", "__cflb=02DiuDSnUsPgiMQzVNimjJdcPn2DXK4ZqAx6U3Qmmk1QQ");
request.AddHeader("Content-Length", "<calculated when request is sent>");
request.AddHeader("Connection", "keep-alive");
//request.AddHeader("Host", "<calculated when request is sent>"); here will be error
request.AddHeader("User-Agent", "PostmanRuntime/7.29.2");
request.AddHeader("Accept-Encoding", "gzip, deflate, br");
request.AddHeader("Postman-Token", "<calculated when request is sent>");
request.AddParameter("organization", "internal-dev");
request.AddFile("images[]", "D:\\CLOUDX\\EyeQTech\\faceid\\itsme.jpg");
request.AddParameter("aliasId", "123_cuong"); // here don't add aliasId prameter
RestResponse response = client.Execute(request);
Console.WriteLine(response.Content); //{messenge: missing aliasID}
}
}
Postman
enter image description here
Here is headers of Postman
enter image description here
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);
I need to call a Post service with RestSharp
var client = new RestClient(url);
var request = new RestRequest(url,Method.POST);
request.AddHeader("Content-type", "application/json");
request.AddJsonBody(new { grant_type = "client_credentials", client_id = clientIdParam, client_secret = appReg_clientSecret, ressource = _ressource }
);
var response = client.Post(request);
The problem is that the request's body is always null and the json body is added as a parameter
Any ideas?
https://login.microsoftonline.com/{{tenantId}}/oauth2/token
seems to not accept json, even with the content-type set as "application/json"
My solution:
var client = new RestClient("https://login.microsoftonline.com");
var request = new RestRequest("/{{tenantId}}/oauth2/token", Method.POST);
var requestBody = $"grant_type=client_credentials&client_id={clientIdParam}&client_secret={appReg_clientSecret}&resource={_resource}";
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", requestBody, ParameterType.RequestBody);
var response = client.Execute(request);
Alright! So I have this Restful call that i am trying to make to a Polycom device.
To sort of isolate within this code I used RestSharp and it works fine. Also removing the credentials object or altering it makes it kick back an unauthorized so i believe authorization is fine. I think its the body/parameters that are incorrect.
//THIS SECTION WORKS
//RestRequest restRequest = new RestRequest();
//restRequest.AddJsonBody(body);
//RestClient restClient = new RestClient(targetUrl);
//restClient.RemoteCertificateValidationCallback = (sPoint, cert, wRequest, certProb) => true;
//restClient.Authenticator = new HttpBasicAuthenticator(username, deskPhone.MACPassword);
//IRestResponse restsharpResponse = await restClient.ExecutePostAsync(restRequest).ConfigureAwait(false);
//END SECTION
What my issue is.. I have no idea why I am getting an error 400 Bad Request. When I look at what I have in the call it all seems to align correctly. The Auth token is the same as RestSharp and the body is the same object.
I really am at a loss for what i can do and unfortunately I cant use restsharp i need to use what is available in Net Core.
I have a few different implementations in the code as you can see below. I attempted with HttpClient and I attempted with HttpWebRequest.
My question is... What likely bug do i have that is preventing this from being a proper request.
This link here is to API documentation which I also seem to be aligning with correctly.
https://support.polycom.com/content/dam/polycom-support/products/voice/polycom-uc/other-documents/en/2018/ucsoftware-restapi.pdf
[HttpPost]
[Route("[action]")]
public async Task PhoneNumberStuff(long userId)
{
DeskPhone deskPhone = DbContext.DeskPhones
.Include(x=>x.DeskPhoneUser)
.FirstOrDefault(x => x.DeskPhoneUserId == 11546);
string targetUrl = $"https://{deskPhone.IPv4Address}/api/v1/callctrl/dial";
string certLcation = #"C:\Users\AlexRoundy\Desktop\Polycom.cer";
string username = "Polycom";
SecureString password = new NetworkCredential("", deskPhone.MACPassword).SecurePassword;
String encoded = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + deskPhone.MACPassword));
//$cred = New - Object System.Management.Automation.PSCredential($username,$password)
NetworkCredential credential = new NetworkCredential(username, password);
string body = #"{""data"":{""Dest"": ""7168675309"", ""Line"": ""1"",""Type"": ""TEL"" } }";
//THIS SECTION WORKS
//RestRequest restRequest = new RestRequest();
//restRequest.AddJsonBody(body);
//RestClient restClient = new RestClient(targetUrl);
//restClient.RemoteCertificateValidationCallback = (sPoint, cert, wRequest, certProb) => true;
//restClient.Authenticator = new HttpBasicAuthenticator(username, deskPhone.MACPassword);
//IRestResponse restsharpResponse = await restClient.ExecutePostAsync(restRequest).ConfigureAwait(false);
//END SECTION
HttpClientHandler handler = new HttpClientHandler();
//handler.SslProtocols = System.Security.Authentication.SslProtocols.Tls11;
handler.ServerCertificateCustomValidationCallback = (sPoint, cert, wRequest, certProb) => true;
//handler.CheckCertificateRevocationList = false;
handler.Credentials = credential;
//handler.ClientCertificateOptions = ClientCertificateOption.Manual;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUrl);
request.ServerCertificateValidationCallback = (sPoint, cert, wRequest, certProb) => true;
request.ContentType = "application/json; charset=utf-8";
request.Method = "POST";
request.Headers.Add("Authorization", "Basic " + encoded);
request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.None;
request.Accept = "application/json";
using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(body);
streamWriter.Flush();
}
HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse();
string responseText;
using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
responseText = streamReader.ReadToEnd();
}
HttpClient httpClient = new HttpClient(handler);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
StringContent temp = new StringContent(body, Encoding.UTF8, "application/json");
HttpRequestMessage httpMessage = new HttpRequestMessage(HttpMethod.Post, targetUrl);
httpMessage.Content = temp;
HttpResponseMessage testA = await httpClient.SendAsync(httpMessage).ConfigureAwait(false);
HttpResponseMessage stuff = await httpClient.PostAsync(targetUrl, temp).ConfigureAwait(false);
handler.Dispose();
httpMessage.Dispose();
httpClient.Dispose();
}
So below are the two comparisons from fiddler.
The problem child is this line here.
request.ContentType = "application/json; charset=utf-8";
The fix??
request.ContentType = "application/json";
The following below is the fiddler results that led to the discovery.
POST https://192.168.50.76/api/v1/callctrl/dial HTTP/1.1
Authorization: Basic UG9seWNvbTp3TUh0bDNKdA==
Accept: application/json, text/json, text/x-json, text/javascript, application/xml, text/xml
User-Agent: RestSharp/106.11.4.0
Connection: Keep-Alive
Accept-Encoding: gzip, deflate
Content-Type: application/json
Content-Length: 60
Host: 192.168.50.76
{"data":{"Dest": "7164171568", "Line": "1","Type": "TEL" } }
POST https://192.168.50.76/api/v1/callctrl/dial HTTP/1.1
Authorization: Basic UG9seWNvbTp3TUh0bDNKdA==
Accept: application/json, text/json, text/x-json, text/javascript, application/xml, text/xml
User-Agent: FauxPaux
Connection: Keep-Alive
Accept-Encoding: deflate
Content-Type: application/json;
Content-Length: 60
Host: 192.168.50.76
{"data":{"Dest": "7164171568", "Line": "1","Type": "TEL" } }
I was search this article Consuming Drupal RestApi with c#
And http://tylerfrankenstein.com/code/drupal-services-csrf-token-firefox-poster
I has question in the cookie and token. I have test in poster with firefox and successful on post the created article .Tamper Data has the request header.
tamper data
nid: "129342"
uri: http://www.tsghy.com.cn/services/node/129342
Postman created the post code
var client = new RestClient("http://www.tsghy.com.cn/services/node");
var request = new RestRequest(Method.POST);
request.AddHeader("postman-token", "5c28c9d6-d640-a4f0-a549-b6018e62907d");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("x-csrf-token", "s0Z17LT7neX_K6grHgoJCUPR6VcL2QxRlNLmbRWeExE");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "type=article&title=test%201", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
I will crazy,
And replace to the C# ,i has Access denied for user anonymous.this my code with below :
First I login the Drupal with Rest
private login_user2 loginAsync2(string username, string password)
{
try
{
RestClient client = new RestClient(base_url2);
var request = new RestRequest("user/login.json", Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
client.Authenticator = new SimpleAuthenticator("username",username,"password",password);
var restResponse = client.Execute(request);
var content = restResponse.Content;
if (restResponse.StatusCode==System.Net.HttpStatusCode.OK)
{
login_user2 loginuser = JsonConvert.DeserializeObject<login_user2>(content.ToString());
request = new RestRequest("session/token", Method.GET);
restResponse = client.Execute(request);
loginuser.session_token = restResponse.Content.ToString();
return loginuser;
}
else {
return null;
}
}
catch (Exception ex) { throw ex; }
}
I have question at the login/user->token and session/token ,which the difference?
Second,Post the create data:
RestClient client = new RestClient(base_url2);
var request = new RestRequest("node", Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/json; charset=UTF-8");
request.AddHeader("Accept", "application/json");
request.AddHeader("cookie", "Drupal.toolbar.collapsed=0; "+current_user2.session_name+"="+current_user2.sessid+"; has_js=1");
request.AddHeader("x-csrf-token",current_user2.session_token);
request.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0");
request.AddParameter("application/json", myjobject, ParameterType.RequestBody);
var queryresult = client.Execute(request);
yes,I found the key,restful has bug at the request.addheader(cookie,cookie);
change to :request.AddParameter(session_name,session_id,parametertype.cookie);