I'm trying to make an API call to third party URL, which is working fine through postman, but same request through C# HttpClient not working.
This is how I'm sending request in postman
C# Sample Code
var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("PARAM1", "PARAM1 Value"));
nvc.Add(new KeyValuePair<string, string>("PARAM2", "PARAM2 Value"));
nvc.Add(new KeyValuePair<string, string>("PARAM3", "PARAM3 Value"));
var req = new HttpRequestMessage(HttpMethod.Post, "Https://ThirdPartyURL") {
Content = new FormUrlEncodedContent(nvc)
};
Am I doing anything wrong here?
UPDATE #1:
**
Fiddler Traces for postman request(which is working fine)
Fiddler Traces for C# Request(which is failing)
Thanks in advance!
Regards,
Moksh
Instead of
var nvc = new List<KeyValuePair<string, string>>();
try to create a new class:
public class RecipientSender
{
public string Recipient_First_Name {get; set;}
public string Recipient_Last_Name {get; set;}
.....
}
and create httpclientrequest like this:
....
....
var recipientSender=new RecipientSender { Recipient_FirstName=..., }
var contentType = new MediaTypeWithQualityHeaderValue("application/json");
httpClient.DefaultRequestHeaders.Accept.Add(contentType);
var stringData = JsonConvert.SerializeObject(recipientSender);
contentData = new StringContent(stringData, Encoding.UTF8, "application/json");
var httpResponseMessage=client.PostAsync(url, contentData);
.....
Related
I have been provided an API with the base URL and the Authentication URL. This API makes use of token authentication. I have written code to authenticate then pass the token to the other URL but keep running into the error below:
Unexpected character encountered while parsing value: <. Path '', line 0, position 0.'
My code is as below
public string Index()
{
var accessToken = string.Empty;
string URL = "https://api.mkoinapp.net/apps/merchants/api/v1/auth/apps/authenticate/";
string _user = "XX";
string _pwd = "XX";
string _clientId = "XXX";
string _clientSecret = "XXXX";
var KeyValus = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("username", _user),
new KeyValuePair<string, string>("password", _pwd),
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("client_id", _clientId),
new KeyValuePair<string, string>("client_secret", _clientSecret)
};
var request = new HttpRequestMessage(HttpMethod.Post, URL + "access_token");
request.Content = new FormUrlEncodedContent(KeyValus);
var client = new HttpClient();
var response = client.SendAsync(request).Result;
using (HttpContent content = response.Content)
{
var json = content.ReadAsStringAsync().Result;
JObject jwtDynamic = JsonConvert.DeserializeObject<dynamic>(json);
// List<Token> jwtDynamic = JsonConvert.DeserializeObject<List<Token>>(json);
var accessTokenExpiration = jwtDynamic.Value<DateTime>("expires_in");
accessToken = jwtDynamic.Value<string>("access_token");
var name = jwtDynamic.Value<string>("name");
var accessexpirationDate = accessTokenExpiration;
Response.Redirect("https://api.mkoinapp.net/apps/merchants/api/v1/iprs?id=" + _user);
}
return accessToken;
}
Any help to resolve this will be apprciated.
You may be experiencing any of these errors:
The response is a bad formatted JSON.
The response is not a JSON (could be an HTML as Casey is mentioning or XML).
The response is an array, you're trying to parse JObject in that case you're going to need JArray.
When I try in postman it working fine and I am getting a response.
I am trying to make a request. and I am not getting any response please look into my code and let me know where I did wrong?
using (var client = new HttpClient())
{
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("client_id", "11223asda"),
new KeyValuePair<string, string>("client_secret", "1232asdasa"),
new KeyValuePair<string, string>("code", "authcode3"),
new KeyValuePair<string, string>("grant_type", "authorization_code"),
new KeyValuePair<string, string>("redirect_uri", "http://www.google.com/")
});
var uri = new Uri("https://sandbox-api.userdomain.com/v2/oauth2/token");
// var content = new FormUrlEncodedContent(obj);
//HttpResponseMessage response = null;
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri);
request.Content = content;
HttpResponseMessage response = await client.SendAsync(request);
Debug.WriteLine(response.StatusCode);
Output :
For this type of work I use this lib :
https://github.com/jgiacomini/Tiny.RestClient
var client = new TinyRestClient(new HttpClient(),"https://sandbox-api.userdomain.com/");
var response = await client.
PostRequest("v2/oauth2/token").
AddFormParameter("client_id", "France").
AddFormParameter("client_secret", "Paris").
AddFormParameter("grant_type", "Paris").
AddFormParameter("redirect_uri", "Paris").
ExecuteAsync<Response>();
Hope that helps!
I am trying to Create a webhook subscription with .net HttpClient() for Calendly
https://developer.calendly.com/docs/webhook-subscriptions
I am attempting to convert this Curl command to .Net
curl --header "X-TOKEN: <your_token>" --data "url=https://blah.foo/bar&events[]=invitee.created&events[]=invitee.canceled" https://calendly.com/api/v1/hooks
Here is my .Net code:
private static async Task<HttpResponseMessage> PostCreateWebhookSubscription()
{
var client = new HttpClient {BaseAddress = new Uri("https://calendly.com")};
var request = new HttpRequestMessage(HttpMethod.Post, "/api/v1/hooks/");
var keyValues = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("url",
"https://requestb.in/17ruxqh1&events[]=invitee.created&events[]=invitee.canceled")
};
request.Content = new FormUrlEncodedContent(keyValues);
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded") {CharSet = "UTF-8"};
request.Content.Headers.Add("X-TOKEN", "<my_calendly_token>");
return await client.SendAsync(request);
}
I get this error 422 error, but unable to figure out what to change to make this work.
getting error Unprocessable Entity
{"type":"validation_error","message":"Validation failed","errors":{"events":["can't be blank"]}}
I am able to run the Curl command and it works fine from the same machine, so I know that is working.
I created a .net HttpClient call to test the basic Token, which worked fine.
Any suggestions?
Finally came back this which figured it out as soon as I looked at the code again.
Originally I was looking at the whole URL as one big string, but did not realize at first the & symbol which was separating the values to pass.
The bad code below:
var keyValues = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("url",
"https://requestb.in/17ruxqh1&events[]=invitee.created&events[]=invitee.canceled")
};
Should have been changed to this seperating each value from their documentation:
var keyValues = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("url","https://requestb.in/17ruxqh1"),
new KeyValuePair<string, string>("events[]","invitee.created"),
new KeyValuePair<string, string>("events[]","invitee.canceled")
};
So for those that want to use .Net to create webhook subscriptions with Calendly here is a full TestMethod code to try it out. Just replace the first parameter with your requestb.in or post url. Also put in your Calendly api key.
[TestMethod]
public void CreateCalendlyWebhookSubscription()
{
var task = PostCreateWebhookSubscription();
task.Wait();
var response = task.Result;
var body = response.Content.ReadAsStringAsync().Result;
}
private static async Task<HttpResponseMessage> PostCreateWebhookSubscription()
{
var client = new HttpClient {BaseAddress = new Uri("https://calendly.com")};
var request = new HttpRequestMessage(HttpMethod.Post, "/api/v1/hooks/");
var keyValues = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("url","https://requestb.in/17ruxqh1"),
new KeyValuePair<string, string>("events[]","invitee.created"),
new KeyValuePair<string, string>("events[]","invitee.canceled")
};
request.Content = new FormUrlEncodedContent(keyValues);
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded") {CharSet = "UTF-8"};
request.Content.Headers.Add("X-TOKEN", "<your Calendly ApiKey>");
return await client.SendAsync(request);
}
Hope this helps somebody!
I have some code that formats a JSON request using RestSharp to access ESRI geocoding API. The code works, but I'm wondering if there is a better way to get the request into the correct format here is a sample of what I have and below a sample of what the request should look like.
request = new RestRequest("geocodeAddresses", Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
//Format the request properly
var attributes = new Dictionary<string, object>();
attributes.Add("OBJECTID", address.Address);
attributes.Add("Address", address.Address);
attributes.Add("City", address.City);
attributes.Add("Region", address.State);
attributes.Add("Postal", address.ZipCode);
JsonObject attributesObj = new JsonObject();
foreach (var parms in attributes)
{
attributesObj.Add(parms);
}
JsonObject recordsObj = new JsonObject();
recordsObj.Add("attributes", attributesObj);
JsonArray EsriRequest = new JsonArray();
EsriRequest.Add(recordsObj);
JsonObject addressObj = new JsonObject();
addressObj.Add("records", EsriRequest);
request.AddParameter("addresses",
addressObj.ToString());
request.AddParameter("token", esriToken.ToString());
request.AddParameter("f", "json");
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
IRestResponse<EsriAddress> responseData = client.Execute<EsriAddress>(request);
Request output sample:
http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/geocodeAddresses?addresses={"records":[{"attributes":{"OBJECTID":1,"Address":"380 New York St.","City":"Redlands","Region":"CA","Postal":"92373"}},{"attributes":{"OBJECTID":2,"Address":"1 World Way","City":"Los Angeles","Region":"CA","Postal":"90045"}}]}&sourceCountry=USA&token=<YOUR TOKEN>&f=pjson
I currently only ever send one address, but in theory the api can take more then one at a time.
Here's how I send a batch of addresses to the geocodeAddresses method in the ArcGIS REST API. I'm not using RestSharp, just HttpClient:
string token = GetToken();
string url = "http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/geocodeAddresses";
using (var client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
var values = new[]
{
new KeyValuePair<string, string>("token", token),
new KeyValuePair<string, string>("forStorage", "true"),
new KeyValuePair<string, string>("MaxBatchSize", "1000"),
new KeyValuePair<string, string>("outFields", "*"),
new KeyValuePair<string, string>("f", "json"),
new KeyValuePair<string, string>("addresses", inputJson) // json string containing an array of a complex type
};
foreach (var keyValuePair in values)
content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
var response = await client.PostAsync(url, content);
Task<string> responseString = response.Content.ReadAsStringAsync();
string outputJson = await responseString;
}
}
I got this url
http://www.stuff.com/ws/BIWS/service.php?key=sdf9&type=find&query=funktioner:orsearch(%224804255620%22)
I need a "post"-api request, with XML returned data.
I need to use a post because get is limited to ~2000 characters, and I need to send a lot of data in orsearch. What am I doing wrong, how can I debug this?
var clientt = new HttpClient();
clientt.BaseAddress = new Uri("http://www.stuff.com");
var request = new HttpRequestMessage(HttpMethod.Post, "/ws/BIWS/service.php?");
var keyValues = new List<KeyValuePair<string, string>>();
keyValues.Add(new KeyValuePair<string, string>("key", "sdf9"));
keyValues.Add(new KeyValuePair<string, string>("type", "find"));
keyValues.Add(new KeyValuePair<string, string>("query", "funktioner:orsearch('4804255620')"));
request.Content = new FormUrlEncodedContent(keyValues);
var response = await clientt.SendAsync(request);
string content = await response.Content.ReadAsStringAsync();
// Error wrong key entered or something, but url works fine