API Post request C# URL - c#

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

Related

Send form-data in C# HttpClient

Hello, I am pulling data from an api with C# HttpClient. I need to pull data in form-data form with the post method. I wrote the code below but got an empty response. How can I do it?
var client = new HttpClient();
client.Timeout = TimeSpan.FromSeconds(300);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var request = new HttpRequestMessage();
request.Method = HttpMethod.Post;
request.RequestUri = new Uri("https://myapi.com");
var content = new MultipartFormDataContent();
var dataContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("value1", "myvalue1"),
new KeyValuePair<string, string>("value2", "myvalue2"),
new KeyValuePair<string, string>("value3", "myvalue3")
});
content.Add(dataContent);
request.Content = content;
var header = new ContentDispositionHeaderValue("form-data");
request.Content.Headers.ContentDisposition = header;
var response = await client.PostAsync(request.RequestUri.ToString(), request.Content);
var result = response.Content.ReadAsStringAsync().Result;
You're sending your data in an incorrect way by using FormUrlEncodedContent.
To send your parameters as MultipartFormDataContent string values you need to replace the code below:
var dataContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("key1", "myvalue1"),
new KeyValuePair<string, string>("key2", "myvalue2"),
new KeyValuePair<string, string>("key3", "myvalue3")
});
With this:
content.Add(new StringContent("myvalue1"), "key1");
content.Add(new StringContent("myvalue2"), "key2");
content.Add(new StringContent("myvalue3"), "key3");

c# post request using httpparams and headers

I had a client app which was written in angular that post requests to connect/token
const body = new HttpParams()
.set('username', email)
.set('password', password)
.set('grant_type', "password")
.set('scope', "offline_access");
const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this.http.post<any>(this._baseAuthUrl + 'connect/token', body, { headers })
Now I have to write this in c#, but stuck with some part
HttpClient httpClient = new HttpClient();
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, "http://mysite/connect/token");
requestMessage.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
How do I add HttpParams and post request properly please?
Here is the code.
var httpClient = new HttpClient();
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("username", email),
new KeyValuePair<string, string>("password", password),
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("scope", "offline_access")
};
var content = new FormUrlEncodedContent(pairs);
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, "http://mysite/connect/token");
requestMessage.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
requestMessage.Content = content;
var response = await httpClient.SendAsync(requestMessage);
The above code is just an example to answer the question. But in your implementation, You should use HttpClient static and initialize it at once. Read more

I am not getting response REST API (POST) Content Type FormUrlEncode

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!

Error creating Calendly webhook subscription with .Net HttpClient()

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!

How to get object using Httpclient with response Ok in Web Api

my web api like
public async Task<IHttpActionResult> RegisterUser(User user)
{
//User Implementation here
return Ok(user);
}
I am using HTTPClient to request web api as mentioned below.
var client = new HttpClient();
string json = JsonConvert.SerializeObject(model);
var result = await client.PostAsync( "api/users", new StringContent(json, Encoding.UTF8, "application/json"));
Where i can find user object in my result request which is implemented on client application?
You can use (depands on what you need), and de-serialize it back to user object.
await result.Content.ReadAsByteArrayAsync();
//or
await result.Content.ReadAsStreamAsync();
//or
await result.Content.ReadAsStringAsync();
Fe, if your web api is returning JSON, you could use
var user = JsonConvert.DeserializeObject<User>( await result.Content.ReadAsStringAsync());
EDIT:
as cordan pointed out, you can also add reference to System.Net.Http.Formatting and use:
await result.Content.ReadAsAsync<User>()
string Baseurl = GetBaseUrl(microService);
string url = "/client-api/api/token";
using (HttpClient client = new HttpClient())`enter code here`
{
client.BaseAddress = new Uri(Baseurl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
List<KeyValuePair<string, string>> keyValues = new List<KeyValuePair<string, string>>();
keyValues.Add(new KeyValuePair<string, string>("client_id", "5196810"));
keyValues.Add(new KeyValuePair<string, string>("grant_type", "password"));
keyValues.Add(new KeyValuePair<string, string>("username", "abc.a#gmail.com"));
keyValues.Add(new KeyValuePair<string, string>("password", "Sonata#123"));
keyValues.Add(new KeyValuePair<string, string>("platform", "FRPWeb"));
HttpContent content = new FormUrlEncodedContent(keyValues);
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
content.Headers.ContentType.CharSet = "UTF-8";
var result = client.PostAsync(url, content).Result;
string resultContent = result.Content.ReadAsStringAsync().Result;
}

Categories