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?
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);
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);
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);
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));
}