I send a request to the API and sometimes receive the response with an HTTP 429 status code (TooManyRequests).
On average, for 10 requests, 2 will return 429 response and the remaining 8 return the correct value.
It also happened to me that when it was the first request (so there is no option for TooManyRequests)
public static List<ResponseObject> GetProductsFromRestAPI(int[] ProductIdArray )
{
List<ResponseObject> products = new List<ResponseObject>();
string action;
for (int i = 0; i < ProductIdArray.Length; i++)
{
action = "products/" + ProductIdArray[i].ToString();
client = AddHeadersToClient(action, new RestClient("https://api.usedbythiscode.com/")); //required by this API.
var currentProduct = RequestsLib.GetProduct(client, action);
products.Add(currentProduct);
}
return products;
}
public static Product GetProduct(RestClient restClient, string action) //todo test this for bugs
{
var result = new Product();
var request = new RestRequest(action, Method.GET);
var response = SendRequest(restClient, request);//Here I sometimes get response with 429.
//.. Other code
return result;
}
public static async Task<IRestResponse> SendRequest(RestClient restClient, RestRequest request)
{
return await restClient.ExecuteGetAsync(request);
}
Temporarily resolved it by sending another request with do while loop and usually second request return right answer.
do
{
SendRequest(restClient, request);
}
while (StatusCode != 200);
Where could the cause of the error lie?
Is it possible that I have unclosed requests?
Is creating multiple RestSharp clients a good practice?
EDIT:
The problem was on the server side. All I had to do was report the bug to the admins who provided the API. Thank you for help.
429 is Too Many Requests. Most APIs have some kind of rate-limiting in place so that a single client can't take down their server with too many requests.
The proper response for 429 is to retry. I recommend using Polly for retry logic, but be aware that HandleTransientHttpError doesn't consider 429 a transient error.
I agree with #mason, you should use async method with Task<> and await response Here is the part of login side of my mobileApp-project in Xamarin. You may want to see how to use async with Task<> easily.
public async Task<BSUser> ValidateUser(string userName, string password)
{
string url = Xamarin.Essentials.Preferences.Get(Constants.URL_KEY, "") + "/api/Validateuser";
HttpClient _Client = new HttpClient();
var data = new Dictionary<string, string>
{
{"userName", userName},
{"password", password}
};
string jsonData = JsonConvert.SerializeObject(data);
HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage httpResponse = await _Client.PostAsync(url, content);
if (httpResponse.IsSuccessStatusCode)
{
try {
var responseData = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
var result = JsonConvert.DeserializeObject(responseData).ToString();
UserInfo userInfo = JsonConvert.DeserializeObject<UserInfo>(result);
BSUser value = new BSUser();
value.UserName = userInfo.userCode;
return value;
}
catch (Java.Net.SocketException e)
{
Console.WriteLine("Hata", e);
return null;
}
}
else
{
return null;
}
}
catch (SystemException)
{
return null;
}
}
Related
I'm creating a Task in C# but I'm not sure what I do is correct. I'm using Restsharp and in Restsharp there are two methods: Execute and ExecuteAsync. I want to do an Async call but I also need to return data to the client without blocking the execution.
Therefore I created a task which will use Execute instead of ExecuteAsync. The reason why is because I have to wait until I get a response back and then return it in the right data structure. So I thought there is no use in using ExecuteAsync if I have to await it in a Task...
My code looks as follows:
public Task<Response> ExecuteAsync()
{
return new Task<Response>(() =>
{
var client = new RestClient(URL);
if (_useBasicAuth)
{
client.Authenticator = new HttpBasicAuthenticator(_username, _password);
}
var request = RequestBuilder(_method);
var response = client.Execute(request);
return new Response()
{
HttpStatusCode = response.StatusCode,
HttpStatusDescription = response.StatusDescription,
Content = response.Content,
Cookies = ExtractCookies(response.Cookies),
Headers = ExtractHeaders(response.Headers)
};
});
}
Is this correct? The client should be able to call ExecuteAsync without blocking the execution.
I strongly suspect you should really just use ExecuteAsync and write an async method:
public async Task<Response> ExecuteAsync()
{
var client = new RestClient(URL);
if (_useBasicAuth)
{
client.Authenticator = new HttpBasicAuthenticator(_username, _password);
}
var request = RequestBuilder(_method);
var response = await client.ExecuteAsync(request).ConfigureAwait(false);
return new Response
{
HttpStatusCode = response.StatusCode,
HttpStatusDescription = response.StatusDescription,
Content = response.Content,
Cookies = ExtractCookies(response.Cookies),
Headers = ExtractHeaders(response.Headers)
};
}
I have code like following
public async Task<object> GetMethod()
{
object result = null;
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, "www.fo");
HttpResponseMessage responseMessage = await client.SendAsync(requestMessage);
if (ok)
{
dynamic data = JObject.Parse(responseMessage.Content.ReadAsStringAsync().Result);
result = data.result.paameter1.tables.paamete2.row.ToString();
}
return result
}
Observation is client.SendAsync(requestMessage); takes too much time , is there any other better way of doing it considering performance ?
this would be better
private async Task<T> Post<T>(string url, object obj) where T : class
{
var jsonString = _jsonHelper.SerializeObject(obj);
var stringContent = new StringContent(jsonString, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(url, stringContent).ConfigureAwait(false);
var responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
if(!response.IsSuccessStatusCode)
{
//throw
}
var responseObj = _jsonHelper.DeserializeObject<T>(responseString);
return responseObj;
}
usage
public Task<SomeTypedObject> DoSomething(int someValue)
{
var url = "someUrl";
var requestObject= new ClassForRequest { proptery1 = someValue};
return Post<SomeTypedObject>(url, requestObject);
}
the main issue with yours i not using await on ReadAsStringAsync, ur is thread blocking.
but i highly suspect this is not the reason for the "performance" you are wanting.
What is the call doing?
how much data is it returning?
how far is the endpoint?/ how powerful is the endpoint machine? / what its ping to that machine?
PS, show your HttpClient life-time, the problem is most likely there.
is performance for you how long it takes for 1 request or its ability to do this x times a minute.
public async Task<>GetLandProperty(string num)
{
var request = new HttpRequestMessage(HttpMethod.Get, _httpClient.BaseAddress+relativeurl);
// added required headers here.
var response = await _httpClient.SendAsync(request);
}
now here response is httpresponsemessage. i dont understand how to extract data out of response and deserialize it. probably i can create class, fetch response's content and deserialise it but what to do if it return failure response or exception. how to return generic type in this case
This is related to your api code. You can catch the exception information and return different information by setting the HttpStatusCode of HttpResponseMessage in the api side.
In the GetLandProperty method, you can set the return type to object to return different content.
Determine the returned content by judging the status of IsSuccessStatusCode of response. If the status is true, use the type returned by deserialize and return the corresponding object. If it is false, return the response directly.
public async Task<object> GetLandProperty()
{
Product product = null;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("url");
var request = new HttpRequestMessage(HttpMethod.Get, client.BaseAddress);
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
string responseString = response.Content.ReadAsStringAsync().Result;
Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(responseString);
product = Newtonsoft.Json.JsonConvert.DeserializeObject<Product>(responseString);
return product;
}
return response;
}
}
My api code:
[HttpGet]
public HttpResponseMessage Get(int id)
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
Product persona = _context.Product.FirstOrDefault(p => p.DataID == id);
if (persona != null)
{
response.Content = new StringContent(JsonConvert.SerializeObject(persona));
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
return response;
}
else
{
response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
response.Content = new StringContent("error message");
return response;
}
}
Update
Another method to receive GetLandProperty method returned content:
public async Task<object> CallTest()
{
var obj = await GetLandProperty();
if(obj is Product)
{
Product product= (Product)obj;
// save data to db
}
else
{
//do other operations
return obj;
}
}
Here is the test result by postman:
I am not very sure whats the question.
To get response data
var result = await response.Content.ReadAsStringAsync();
and to desriazile it
var json= JsonConvert.DeserializeObject<T>(result);
I wrote a function using GetAsync() which works fine, but now i'd like to expand on it using SendAsync() instead [for POSTing and sofourth]; however my SendAsync() version is not working as expected, it returns a 422 unprocessible entity. (no IDE atm; sorry for minor typos)
init
var Client = new HttpClient{
BaseAddress = "https://example.com"
}
Client.DefaultRequestHeaders.UserAgent.ParseAdd("Project/1.0 (blah blah)");
...
Working GetAsync()
public async Task<string> GetResponse(string user, string pass){
var uri = $"/user/login.json?name={user}&password={pass}";
var req = await Client.GetAsync(uri);
return req.Content.Request.Content.ReasStringAsync();
}
non working SendAsync()
public async Task<string> GetResponse(string page, Dictionary<string, string> args){
//assume page = "/user/login.json" and args == {"username", "user"},{"password", "pass"}
try{
var req = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(page),
Content = new FormUrlEncodedContent(args),
}
var response = await Client.SendAsync(req);
if(response.IsSuccessStatusCode){
return await response.Content.ReasStringAsync();
return null;
}
catch{ return null }
}
note: along with the 422, the response still contains json which states "invalid Auth Token!"
What is GetAsync() doing that SendAsync() is not?
Your Send included content in the BODY of a HTTP GET request.
HTTP GET requests should not have a BODY and there are servers that wont process such requests.
Convert the dictionary to a QueryString and include it in the URI.
public async Task<string> GetResponse(string page, Dictionary<string, string> args) {
//assume page = "/user/login.json" and args == {"username", "user"},{"password", "pass"}
try {
QueryString queryString = QueryString.Create(args);
var uri = new Uri(page + queryString.ToString());
var request = new HttpRequestMessage(HttpMethod.Get, uri);
var response = await Client.SendAsync(request);
if(response.IsSuccessStatusCode){
return await response.Content.ReadAsStringAsync();
return string.Empty;
} catch { return string.Empty; }
}
Your code snippets don't show it, but are you sure the second query's URL has
$"/user/login.json?name={user}&password={pass}"
and not
$"/user/login.json"
?
I need to send this HTTP Post Request:
POST https://webapi.com/baseurl/login
Content-Type: application/json
{"Password":"password",
"AppVersion":"1",
"AppComments":"",
"UserName":"username",
"AppKey":"dakey"
}
It works great in RestClient and PostMan just like above.
I need to have this pro-grammatically and am not sure if to use
WebClient, HTTPRequest or WebRequest to accomplish this.
The problem is how to format the Body Content and send it above with the request.
Here is where I am with example code for WebClient...
private static void Main(string[] args)
{
RunPostAsync();
}
static HttpClient client = new HttpClient();
private static void RunPostAsync(){
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
Inputs inputs = new Inputs();
inputs.Password = "pw";
inputs.AppVersion = "apv";
inputs.AppComments = "apc";
inputs.UserName = "user";
inputs.AppKey = "apk";
var res = client.PostAsync("https://baseuriplus", new StringContent(JsonConvert.SerializeObject(inputs)));
try
{
res.Result.EnsureSuccessStatusCode();
Console.WriteLine("Response " + res.Result.Content.ReadAsStringAsync().Result + Environment.NewLine);
}
catch (Exception ex)
{
Console.WriteLine("Error " + res + " Error " +
ex.ToString());
}
Console.WriteLine("Response: {0}", result);
}
public class Inputs
{
public string Password;
public string AppVersion;
public string AppComments;
public string UserName;
public string AppKey;
}
This DOES NOW WORK and responses with a (200) OK Server and Response
Why are you generating you own json?
Use JSONConvert from JsonNewtonsoft.
Your json object string values need " " quotes and ,
I'd use http client for Posting, not webclient.
using (var client = new HttpClient())
{
var res = client.PostAsync("YOUR URL",
new StringContent(JsonConvert.SerializeObject(
new { OBJECT DEF HERE },
Encoding.UTF8, "application/json")
);
try
{
res.Result.EnsureSuccessStatusCode();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
You are not properly serializing your values to JSON before sending. Instead of trying to build the string yourself, you should use a library like JSON.Net.
You could get the correct string doing something like this:
var message = JsonConvert.SerializeObject(new {Password = pw, AppVersion = apv, AppComments = acm, UserName = user, AppKey = apk});
Console.WriteLine(message); //Output: {"Password":"password","AppVersion":"10","AppComments":"","UserName":"username","AppKey":"dakey"}
var client = new RestClient("Your URL");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("apk-key", apk);
//Serialize to JSON body.
JObject jObjectbody = new JObject();
jObjectbody.Add("employeeName", data.name);
jObjectbody.Add("designation", data.designation);
request.AddParameter("application/json", jObjectbody, ParameterType.RequestBody);
try
{
var clientValue= client.Execute<Response>(request);
return RequestResponse<Response>.Create(ResponseCode.OK, "", clientValue.Data);
}
catch (Exception exception)
{
throw exception;
}
I made a tools to do it quick and easy:
Install-Package AdvancedRestHandler
or
dotnet add package AdvancedRestHandler
AdvancedRestHandler arh = new AdvancedRestHandler("https://webapi.com/baseurl");
var result = await arh.PostDataAsync<MyLoginResponse, MyLoginRequest>("/login", new MyLoginRequest{
Password = "password",
AppVersion = "1",
AppComments = "",
UserName = "username",
AppKey = "dakey"
});
public class MyLoginRequest{
public string Password{get;set;}
public string AppVersion{get;set;}
public string AppComments{get;set;}
public string UserName{get;set;}
public string AppKey{get;set;}
}
public class MyLoginResponse {
public string Token{get;set;}
}
Extra:
One other thing you can do is to use ArhResponse:
Either this way, in the class definition:
public class MyLoginResponse: ArhResponse
{
...
}
Or this way, in the API call:
var result = await arh.PostDataAsync<ArhResponse<MyLoginResponse>, MyLoginRequest> (...)
and instead of try or cache, check your API call state using simple if statements:
// check service response status:
if(result.ResponseStatusCode == HttpStatusCode.OK) { /* api receive success response data */ }
// check Exceptions that may occur due to implementation change, or model errors
if(result.Exception!=null) { /* mostly serializer failed due to model mismatch */ }
// have a copy of request and response, in case the service provider need your request response and they think you are hand writing the service and believe you are wrong
_logger.Warning(result.ResponseText);
_logger.Warning(result.RequestText);
// Get deserialized verion of, one of the fallback models, in case the provider uses more than one type of data in same property of the model
var fallbackData = (MyFallbackResponse)result.FallbackModel;
Header Possible Issue
There are cases that the Server does not accept C# request due to the header that the HttpClient generates.
It is because HttpClient by default uses the value of application/json; charset=utf-8 for Content-Type...
For sending only application/json part as Content-Type and ignore the ; charset=utf-8 part, you can do as following:
For HttpClient you can fix it by looking into this thread: How do you set the Content-Type header for an HttpClient request?
As for (AdvancedRestHandler) ARH, I fixed it due to integration with some company, but I don't remember fully... I did it, either through options like of requests or through resetting the header value.
we will use HttpPost with HttpClient PostAsync for the issue.
using System.Net.Http;
static async Task<string> PostURI(Uri u, HttpContent c)
{
var response = string.Empty;
using (var client = new HttpClient())
{
HttpResponseMessage result = await client.PostAsync(u, c);
if (result.IsSuccessStatusCode)
{
response = result.StatusCode.ToString();
}
}
return response;
}
We will call it by creating a string that we will use to post:
Uri u = new Uri("http://localhost:31404/Api/Customers");
var payload = "{\"CustomerId\": 5,\"CustomerName\": \"Pepsi\"}";
HttpContent c = new StringContent(payload, Encoding.UTF8, "application/json");
var t = Task.Run(() => PostURI(u, c));
t.Wait();
Console.WriteLine(t.Result);
Console.ReadLine();