HttpClient PostAsync for JSON - c#

I am trying to use the Google OAuth and I have the first part done but now it want's me to POST the following:
code= client_id= client_secret= redirect_uri= grant_type=authorization_code
Currently I am trying to do:
var http = new HttpClient();
http.MaxResponseContentBufferSize = Int32.MaxValue;
var response = await http.GetStringAsync(uri);
That will send but get an error back as it's requesting I do Post sending (could use PostAsync) but I have no content to send to "POST" and it's supposed to return a JSON Feed...
Any ideas?

Related

ASP.net MVC clients consume patch API get Bad request 400 returns

I'm using asp.net MVC 5 to consume API that also developed in asp.net MVC.
For POST and GET requests, I managed to make it work, except for PATCH that always get 400 bad request from web service.
This is what I do in my client controller:
using (HttpClient httpClient1 = new HttpClient())
{
string apiURLGetClientApproval = "/clients/approvals?action=" + actionType;
HttpMethod method = new HttpMethod("PATCH");
HttpRequestMessage message = new HttpRequestMessage(method, new Uri(baseAddress + apiURLGetClientApproval));
StringContent content = new StringContent(json, Encoding.UTF8, "application/json");
httpClient1.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token.AccessToken);
message.Content = content;
var result = httpClient1.SendAsync(message).Result;
}
This is the content that I pass from my client to API:
{{"clients": [
{
"cn": "1132196",
"hitdate": "04/05/2021"
}]}}
PS :
I access API by postman and ajax from client side with this content, got success reponse.
I have tried with these solution, but same 400 error bad request responsed : PATCH Async requests with Windows.Web.Http.HttpClient class
This is how the parameter of API look like:
[CustomAuth(Roles = "Super Admin, Admin, User")]
[HttpPatch]
[Route("clients/approvals")]
public HttpResponseMessage UpdateClientApproval(HttpRequestMessage request, string action, [FromBody]JObject data)
{..... }
I have been dealing with the same exact problem for 2 days now. I just fixed it. I realised that sending a PATCH request probably required some specific payload [{"op":"replace"....}] as we can tell from using PostMan. However the PUT request doesn't, in fact most of the data on the business object would already be populated, so you modify what you want to change and send a PUT request instead. I just did that. I had to add the PUT action method in my controller and change the HttpClient to send a PUT request and it worked less than 5mins ago.

Receive data from server using POST method and with a request body using WebClient in C#

I am trying to receive data back from the server using POST method and the request should have a body. I am using WebClient for this and trying to get the response back in string. I know we can use HttpClient to achieve this. But I want to use WebClient for this specific instance.
I went through this post and tried UploadString and the response gives me a 400 BAD Request.
using (var wc = new WebClient())
{
wc.Headers.Add("Accept: application/json");
wc.Headers.Add("User-Agent: xxxxxxx");
wc.Headers.Add($"Authorization: Bearer {creds.APIKey.Trim()}");
var jsonString = JsonConvert.SerializeObject(new UserRequestBody
{
group_id = userDetails.data.org_id
});
var response = wc.UploadString("https://api.xxxxx.yyy/v2/users", "POST", jsonString);
}
I tested the end point using Postman (with the request header having an api key and the request body in JSON) and it works fine.
I know I haven't formatted the request right. Can someone please help me.
Big Thanks to #Santiago Hernández. The issue was using wc.Headers.Add("Accept: application/json"); in the request header. Changing it to wc.Headers.Add("Content-Type: application/json"); returned a 200 Ok response. The code modification is as follows
using (var wc = new WebClient())
{
wc.Headers.Add("Content-Type: application/json");
wc.Headers.Add("User-Agent: xxxxxxx");
wc.Headers.Add($"Authorization: Bearer {creds.APIKey.Trim()}");
var jsonString = JsonConvert.SerializeObject(new UserRequestBody
{
group_id = userDetails.data.org_id
});
var response = wc.UploadString("https://api.xxxxx.yyy/v2/users", "POST", jsonString);
}
Accept tells the server the kind of response the client will accept and Content-type is about the payload/content of the current request or response. Do not use Content-type if the request doesn't have a payload/ body.
More information about this can be found here.

RestSharp "Not found" response

I'm trying to use the Youtube Data API v3 with RestSharp. Problem is: I get the response: "Not found" when I try to send a request.
var client = new RestClient("https://www.googleapis.com/youtube/v3/channels?part=statistics");
var request = new RestRequest(Method.POST);
request.AddParameter("key", my api key);
request.AddParameter("id", my channel id);
request.AddParameter("fields", "items/statistics/subscriberCount");
IRestResponse response = client.Execute(request);
var content = response.Content;
Console.WriteLine(response.Content);
this.BeginInvoke((System.Windows.Forms.MethodInvoker)delegate () { label1.Text = response.Content; });
This seems to be a problem with RestSharp or the code because in the Google API explorer thing you can test out the inputs and it works there.
I was trying the same thing today and was stuck on the same step. With an hour of effort I figured out.
In the RestClient(baseUri) constructor, just pass the base url and not the whole path.
While initializing RestClient(resource, Method), pass the path as resource and method will be the second parameter.

Setting up a REST Client Application (Post) from a Web API

I've been having a few issues in trying to retrieve the results of a POST operation from a Web Service.
I have been using a chrome extension to test the API Services and they are working there. However I've been having problems on implementing it in code.
This is an example of usage of the chrome extension:
What I'm trying to retrieve on code, is the last part, the json array that the POST operation generates, where it says accessToken.
However, in the code that I've been using below, I've only had access to the status (200 OK) etc.
Here's a preview of the code I am using:
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url.Text);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(header.Text));
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url.Text);
request.Content = new StringContent(body.Text, Encoding.UTF8, header.Text);
client.SendAsync(request)
.ContinueWith(responseTask =>
{
MessageBox.Show(responseTask.Result.Content.Headers.ToString());
}
);
}
The Header.Text is exactly "application/json", the body.Text is body which has those various properties such as username and password (in string format) and url.Text contains the complete URL to call the Web service.
I'd like to know what I'm doing wrong with my code, and what can I do to obtain that json array that contains the accessToken
In your code you need to use ReadAsStringAsync method to convert your HttpContent object to string/json. For example:
client.SendAsync(request)
.ContinueWith(responseTask =>
{
var jsonString = responseTask.Result.Content.ReadAsStringAsync().Result;
MessageBox.Show(jsonString);
});
then you can convert you jsonString as you need.

Status request 404 for Json data in wp8.1

In my application I passed a request api url and when I try to open the link it shows the Json data in the browser. But when I try to deserialize the Json data I got 404 status.
Uri geocodeRequest = new Uri(string.Format("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=17.4271,078.4466&radius=500&type=petrol_bunk&key=MyKey"));
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(geocodeRequest);
if(response.IsSuccessStatusCode==true)
{
When I open this link I can see the Json data but when I try this link in my code the status shows 404 error(No data resources). Also please check this link for the image displayed while debugging my project
It should be about the refuse from the server.
The different between using HttpClient & Web browser to browse website is
"You don't have the same header and method"
Let's try adding other header parameters like Agent,Content-type, Content-length
var client = new HttpClient();
var request = new HttpRequestMessage() {
RequestUri = new Uri("http://www.someURI.com"),
Method = HttpMethod.Get,
...........
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain")); }

Categories

Resources