Passing data from POSTMAN as x-www-form-urlencoded
Key and values are as follows:
data : P1;P2
format : json
Corresponding curl code from POSTMAN
curl --location --request POST 'https://ap-url/id/' \
--header 'content-type: application/x-www-form-urlencoded' \
--data-urlencode 'data=P1;P2' \
How to send the data as x-www-form-urlencoded on HttpClient?
Use https://curl.olsh.me/ for curl commands to C# code
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api-url/id"))
{
var contentList = new List<string>();
contentList.Add($"data={Uri.EscapeDataString("P1;P2")}");
contentList.Add($"format={Uri.EscapeDataString("json")}");
request.Content = new StringContent(string.Join("&", contentList));
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
var response = await httpClient.SendAsync(request);
}
}
The best Pattern is to set a dictionary and send this dictionary data in the post method
var client = _clientFactory.CreateClient("mobile-server");
var data = new[]
{
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("client_id",
_configuration.GetValue<string>("MobileTop:ClientId")),
new KeyValuePair<string, string>("client_secret",
_configuration.GetValue<string>("MobileTop:ClientSecret")),
};
var response =
await client.PostAsync("api/v2/connect/token", new FormUrlEncodedContent(data));
Related
private async Task GetresultAsync()
{
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("https://api.foursquare.com/v3/places/search?ll=15.3494005,75.142583&query=shops&fields=geocodes,categories,name,hours,fsq_id,price,rating,stats,location"),
Headers =
{
{ "Accept", "application/json" },
{ "Authorization", "fsq322aNlTt3+PuRKw5js/ndngtry/XxNV0Q70yzKjDTQn0="
},
},
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
Debug.WriteLine(body);
}
Please any suggestions? I'm very new to xamarin and I'm getting data in postman but not getting result in xamarin using
RESTCLIENT OR HTTPCLIENT for( foursqaure places api for v3) where am I wrong?
I have a Aspnet Core API thats trying to connect to a Microsoft Dynamics 365 instance. The goal is to push data to the CRM Instance using an API.
In order to do this, I have a CRM User and a Pass and my understanding is I will need an OAuth token to actually complete my request.
How can I go about getting that OAuth token from an API ?
My current (non working) code looks like this:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(CrmFInanceCCNotifyDto.Instance.CrmBaseUri);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes($"{CrmFInanceCCNotifyDto.Instance.CrmUser}:" +
$"{CrmFInanceCCNotifyDto.Instance.CrmPass}")));
client.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
client.DefaultRequestHeaders.Add("OData-Version", "4.0");
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Add("If-Match", "*");
var method = "PATCH";
var httpVerb = new HttpMethod(method);
string path = client.BaseAddress + CrmFInanceCCNotifyDto.Instance.CrmLocationUpdateUri;
string jsonPayload = "{\"entity.dfnd_financingused\": 1}";
var stringContent = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
var httpRequestMessage =
new HttpRequestMessage(httpVerb, path)
{
Content = stringContent
};
try
{
var response = await client.SendAsync(httpRequestMessage);
Any pointers in solving this will be much appreciated.
Thanks
I am trying to make a http post via uri using HttpClient like below.
var request = new Dictionary<string, string>();
request.Add("FirstName", "Sibi");
var requestData= new FormUrlEncodedContent(request);
var httpClient= new HttpClient(new HttpClientHandler
{
AllowAutoRedirect = true,
Credentials = new NetworkCredential
{
UserName = settings.Username,
Password = settings.Password
},
CookieContainer = new CookieContainer(),
});
// Set the base address
httpClient.BaseAddress = new Uri(settings.Url);
var req = new HttpRequestMessage(HttpMethod.Post, uri)
{
Content = requestData
};
var httpResponse = await httpClient.SendAsync(req);
But somehow to the target url request is going via Body. I checked in fiddler and it looks like below
POST http://localhost:65518/api/Employee/Create HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Connection: Keep-Alive
Content-Length: 45
Host: localhost:65518
FirstName=Sibi&LastName=P.G&Age=23&Salary=100
I don't have any clue why it is not going via Uri. Any help will be really appreciated. I am trying to hit a local url(running in IIS express with VS 2015). I am in .net core 1.0.1
I have the following code:
var Client = new System.Net.WebClient();
var Response = Client.UploadString("myurl", PostData);
it works as expected
I am trying to do the same with Restsharp:
var Client = new RestClient("myurl");
var Request = new RestRequest(Method.POST);
Request.AddBody(PostData);
var Response = client.Execute(request);
doesn't work, and:
var Client = new RestClient("myurl");
var Request = new RestRequest(Method.POST);
Request.AddParameter("application/x-www-form-urlencoded; charset=UTF-8", PostData);
var Response = client.Execute(request);
doesn't work either...
what am I missing?
I want get Location in Response Header but i can't see this in Response. How to get this. Please help me.
var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false });
FormUrlEncodedContent postData = new FormUrlEncodedContent(new[] {
new KeyValuePair<string,string>("background","1"),
new KeyValuePair<string,string>("line1","Content1"),
new KeyValuePair<string,string>("line2","Content2")
});
HttpResponseMessage response = await client.PostAsync("URL", postData);
string rp = await response.Content.ReadAsStringAsync();