I have the following code as a start to create a API Call to https://jsonplaceholder.typicode.com/posts/. I want to practice making the call, receive a JSON response and then..do stuff.
How can I finish this off to get a response so I can iterate through the response array.
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(URL);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get,"");
request.Content = new StringContent(URL, Encoding.UTF8,"application/json");
Wiring this in VS Code so will need to install packages if needed.
Thank you!
You are almost there. Try (if you want a simple synchronous send):
HttpClient client = new HttpClient();
string responseString;
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, new Uri("<insert your URL>"))) {
HttpResponseMessage response = client.SendAsync(request).Result;
// Get the response content as a string
responseString = response.Content.ReadAsStringAsync().Result;
}
Note that it's good practice to initialize one instance of HttpClient and reuse it to send multiple requests (rather than initialize one every time you need to send something).
Any headers, URLs and such specific to a message should be set in the HttpRequestMessage class (which should be disposed of with the "using ..." term.
Related
At the moment I am using the following RestSharp request to get a website's content:
var client = new RestClient(productLink);
var request = new RestRequest(Method.GET);
request.AddHeader("Cookie", "insert-cookie-content");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
I have tried converting it into HttpClient as i will need to use the AllowRedirect property later:
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Cookie", "insert-cookie-content");
var response = await client.GetAsync(productUrl);
Console.WriteLine(response);
The URL I am trying to get a response from is: https://www.nike.com/sg/launch/t/air-max-90-orange-duck-camo
My first problem is that the HttpClient request is giving me 403 Errors whereas the RestClient request was working fine. How can I fix this?
My second problem is that the cookie expires after a couple of uses, and I have to manually get a new one from postman and insert it. Is there anyway for the request to generate its own cookie?
Here is the two fiddler responses compared: https://imgur.com/a/bZo7d9F
In case of HttpClient if you want to pass the Cookies manually through the DefaultRequestHeaders then you have to tell this to the HttpClient to do NOT use CookieContainer. You have to use HttpClientHandler's UseCookie flag to indicate it.
var client = new HttpClient(new HttpClientHandler { UseCookies = false });
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Cookie", "insert-cookie-content");
var response = await client.GetAsync(productUrl);
Console.WriteLine(response);
I'm using HttpClient in .Net core 3.1. Most of my requests follow a similar pattern regardless of the HTTP method used:
build URL
build (optional) JSON payload
send request
await response
check status code
parse (optional) JSON response
so I've built a wrapper function that does all these things, and it takes the HTTP method as a parameter. However, when it comes to the "send request" step, I need to use a switch statement to invoke the appropriate method on HttpClient to invoke.
I'm sure that under the skin, get GetAsync() PostAsync() etc. are calling the same underlying function and passing the Http method as a parameter. but I can't see any way of calling it like this from the outside. It seems a strange omission as in my experience most HTTP libraries work that way.
Hope this will help you.
// For JsonConvert use Newtonsoft.Json
string url = "YourURL";
string body = JsonConvert.SerializeObject(BodyModel);
string headerParameter = "ASD123456789";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Content-Type of request, it can be application/xml to other
client.DefaultRequestHeaders.Add("Device", headerParameter ); // first is name, second one is value
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url) // there you can have Get, Post, Put, Delete and etc. And every request needs to be configured by its settings
{
Content = new StringContent(body, Encoding.UTF8, "application/json")
};
HttpResponseMessage response = await client.SendAsync(request);
if ((int)response.StatusCode == 200)
{
string responseString = await response.Content.ReadAsStringAsync();
ResponseModel responseModel = JsonConvert.DeserializeObject<ResponseModel>(responseString);
}
When I try to do the code below, it just results in Invalid Content Type (with error number 612).
I'm trying to delete a lead id from a static list. I can add lead ids or get the static list leads fine.
The post and get calls I make are working fine, although the post calls I make seem to require the data right on the url string (as in $"{endpointURL}/rest/v1/lists/{listID}/leads.json?id={leadID}"; If I include the id as a json object, it fails too. This might be a clue to what I'm doing wrong with the delete call.
string url = $"{endpointURL}/rest/v1/lists/{listID}/leads.json?id={leadID}";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Authorization = new
AuthenticationHeaderValue("Bearer", _access_token);
HttpResponseMessage response = await client.DeleteAsync(url);
The response here always results in Invalid Content Type.
If I add this line before I do the deleteasync call, it gives me a different error before it even hits the deleteAsync call.
client.DefaultRequestHeaders.Add("Content-Type", "application/json");
Error is "Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects."
Try using HttpRequestMessage in your code like this
string url = $"{endpointURL}/rest/";
HttpClient client = new HttpClient
{
BaseAddress = new Uri(url)
};
//I'm assuming you have leadID as an int parameter in the method signature
Dictionary<string, int> jsonValues = new Dictionary<string, int>();
jsonValues.Add("id", leadID);
//create an instance of an HttpRequestMessage() and pass in the api end route and HttpMethod
//along with the headers
HttpRequestMessage request = new HttpRequestMessage
(HttpMethod.Delete, $"v1/lists/{listID}") //<--I had to remove the leads.json part of the route... instead I'm going to take a leap of faith and hit this end point with the HttpMethod Delete and pass in a Id key value pair and encode it as application/json
{
Content = new StringContent(new JavaScriptSerializer().Serialize(jsonValues), Encoding.UTF8, "application/json")
};
request.Headers.Add("Bearer", _access_token);
//since we've already told the request what type of httpmethod we're using
//(in this case: HttpDelete)
//we could just use SendAsync and pass in the request as the argument
HttpResponseMessage response = await client.SendAsync(request);
The solution turned out to be a combination of a couple of suggestions.
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Delete, data);
// The key part was the line below
request.Content = new StringContent(string.Empty, Encoding.UTF8, "application/json");
if (!string.IsNullOrEmpty(_access_token))
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _access_token);
}
HttpResponseMessage response = await client.SendAsync(request);
This worked for me.
I'm building an Android app that sends binary data to the server using HttpClient PostAsJsonAsync method. Is is possible to track the progress of the data being sent?
I'm using the code below to send the data to the server:
var client = new HttpClient();
client.BaseAddress = uri;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/bson"));
var result = client.PostAsJsonAsync(uri, fileBytes);
Implement your http post using an AsyncTask. By using this task you can track the progress of the task.
im using PostAsync to call my external webAPI programatically in my back end.
I have had the method working using a httpget, however turning it into a post seems more problematic, due to the httpcontent object required. when awaiting, the status code is always a 404 due to the data not being passed over.
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:52715/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var data = JsonConvert.SerializeObject(new { user = "JOHNSMITH" });
HttpResponseMessage response = await client.PostAsync("MessageUser", new StringContent(data, Encoding.UTF8, "text/json"));
if (response.IsSuccessStatusCode)
{
Console.WriteLine("\n sent signal to dept");
}
}