I use xamarin forms to create an mobile app for Android and iOS. I need to make Http Request, so I use HttpClient.
Here is a simple code of request :
var client = new HttpClient();
try
{
string requestUrl = URL_DATABASE + "xxx";
var content = new StringContent("{\"param\":\"" + param+ "\"}", Encoding.UTF8, "application/json");
var response = await client.PostAsync(requestUrl, content);
if (response.StatusCode == HttpStatusCode.OK)
{
var result = await response.Content.ReadAsStringAsync();
return result;
}
return "{\"status\":-1}";
}
catch (Exception ex) // Error catched : "the request timed out"
{
return "{\"status\":-1}";
}
I used Postman to check result of my request and work's well, I got good response without timeout.
I noticed that error occurs sometimes but can last an hour.
error : the request timed out
Thank you in advance for your help
Related
I've been trying to create a function that validates my token and it works for Android but not for IOS. The response on IOS from my custom API returns 401 unauthorized (which it should when you send an invalid key), but I've tried the key in postman and it's valid.
Maybe this has something to do with formatting? But I don't see what would be the difference between Android and IOS.
Some code:
public async Task<T> PostResponse<T>(string weburl, string jsonstring) where T : class
{
var Token = App.TokenDatabase.GetToken();
string ContentType = "application/json";
var token = string.Format("Token token={0}", Token.access_token);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
try
{
var result = await client.PostAsync(weburl, new StringContent(jsonstring, Encoding.UTF8, ContentType));
if(result.StatusCode == System.Net.HttpStatusCode.OK)
{
var JsonResult = result.Content.ReadAsStringAsync().Result;
try
{
var ContentResp = JsonConvert.DeserializeObject<T>(JsonResult);
return ContentResp;
}
catch { return null; }
}
}
catch { return null; }
return null;
}
I've created some logs on the server side and when I run the IOS app the token doesn't get passed on to the server for some reason.
PHP code:
$token = null;
$headers = apache_request_headers();
if(isset($headers['Authorization'])){
$matches = array();
preg_match('/Token token=(.*)/', $headers['Authorization'], $matches);
if(isset($matches[1])){
$token = $matches[1];
}
}
file_put_contents('../config/log.txt', $token);
I've checked that the app sends the token. It disappears somewhere on the way.
EDIT: After some logging, I found out that the token is in the header but not in the Authorization header when sent through IOS, how do you solve this?
I solved it by downloading Flurl and Flurl.Http plugins and added this line:
var result = await url.WithOAuthBearerToken(token).PostJsonAsync(jsonstring);
Credit: Xamarin forms not sending Authorization header
Also
Fluent HTTP
Query is made from a httpclient hosted in WPF control to azure server and azure server sends the results back to WPF control. When the Internet connection is disabled and postasync query is made httprequestexception is thrown. When the internet connection is restored and postaysnc query is made , post async works fine and if i disable the internet connection again and make the post async throws the exception. Once the internet connection is reestablished the postasync throws the httprequest exception. How to resolve this issue.
var httpContent = new StringContent(value, Encoding.UTF8, "application/json");
var queryUri = new Uri(httpClient.BaseAddress, "content/resultvalue");
var response = await httpClient.PostAsync(queryUri, httpContent);
response.EnsureSuccessStatusCode();
var resultJson = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<Result>(resultJson);
That is the expected behavior. If it cannot connect to the server, an exception is thrown. This is described in the documentation for HttpClient.PostAsync under the Exception Handling heading.
If you need to catch the exception, then put it in a try/catch block and do something with the exception.
var httpContent = new StringContent(value, Encoding.UTF8, "application/json");
var queryUri = new Uri(httpClient.BaseAddress, "content/resultvalue");
try {
var response = await httpClient.PostAsync(queryUri, httpContent);
response.EnsureSuccessStatusCode();
var resultJson = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<Result>(resultJson);
} catch (Exception e) {
//report the exception to the user
}
Well, I am working on creating Quickbook online entries, and for some reason I am getting error (400 bad request).
I know something is invalid in my request but I am unable to figure it out. I am using Sandbox account. I have copied default data from API explorer and made request using this data only and finally getting 400 bad request.
My code is working fine for "Select * from invoice" query request.
The base URL I am using sandbox-quickbooks.api.intuit.com
My Code is as Follow:-
var principal = User as ClaimsPrincipal;
Session["realmId"] = XXXXXXX;
var result = new HttpResponseMessage();
if (Session["realmId"] != null)
{
string realmId = Session["realmId"].ToString();
string qboBaseUrl = ConfigurationManager.AppSettings["QBOBaseUrl"];
//add qbobase url and query
string uri = string.Format("{0}/v3/company/{1}/invoice", qboBaseUrl, realmId);
try
{
var client = new HttpClient();
client.DefaultRequestHeaders.Add("Accept", "application/json;charset=UTF-8");
client.DefaultRequestHeaders.Add("ContentType", "application/json;charset=UTF-8");
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + Session["AccessToken"]);
result = await client.PostAsync(uri, new StringContent(JsonData, System.Text.Encoding.UTF8, "application/json"));
return result;
}
catch (Exception ex)
{
return result;
}
}
else
return result;
Check the body of the response and see if it provides any details about what is wrong with the request.
//...
var responseContent = await result.Content.ReadAsStringAsync();
//...
I am writing an Xamarin.Android app that posts data to Net Core web app with ADAL authentication. The problem is that the API controller is set so it does not require authentication ([AllowAnonymous]), but one and only one of my httpClient.PostAsync() methods responds with the Microsoft Login page. I have tried to use WebClient.UploadString() and the response is the same Login page. I am porting this app from UWP and the same code works there without any problem.
Edit:
Adding some code for more information. The problem is that response.IsSuccessStatusCode is true, but the responseString contains the Microsoft Login page, but it should come back with json data.
HttpResponseMessage response;
try
{
response = await httpClient.PostAsync(url, new System.Net.Http.StringContent(JsonConvert.SerializeObject(data), System.Text.Encoding.UTF8, "application/json"));
}
catch (Exception ex)
{
return result;
}
if (response.IsSuccessStatusCode)
{
var responseString = await response.Content.ReadAsStringAsync();
try
{
//parsing the response
}
catch (Exception)
{
//response was incorrect
}
}
Try this :
HttpContent content = response.Content;
var json = await content.ReadAsStringAsync();
The code goes below
public static async Task<string> getForwardUrl(string url)
{
try
{
HttpClient client = new HttpClient();
HttpRequestMessage forwardRequest = new HttpRequestMessage();
forwardRequest.RequestUri = new Uri(url);
HttpResponseMessage Message = await client.SendAsync(forwardRequest);
return Message.RequestMessage.RequestUri.OriginalString;
}
catch (Exception ex)
{
WriteLine(ex.Message);
}
//...
}
When I run this in a uwp project, exception occurs. The message of this exception shows that the redirection request would change the safe connection to an unsafe one(After that , I checked the URL of the login page , It's https ,but the page after I logged in is http).
I find a similar question, he recommends using Windows.Web.Http instead of System.Net.Http but I get the same error message.
Thanks for your reply
EDIT:
The URL is: https://tinyurl.com /57muy (remove the space) or short a http url with tinyurl.com! The problem only occurs with a shortet http side!
Error: An error occurred while sending the request. Innermessage: Error message not found for this error
According to your description, I'd suppose you are developing a UWP app. And as you've mentioned, we got the exception here because the redirection request would change the safe connection to an unsafe one. To solve this problem, we can turn off auto-redirect and do the redirection by ourselves.
For example:
public static async Task<string> getForwardUrl(string url)
{
var handler = new System.Net.Http.HttpClientHandler();
handler.AllowAutoRedirect = false;
var client = new System.Net.Http.HttpClient(handler);
var response = await client.GetAsync(url);
if (response.StatusCode == System.Net.HttpStatusCode.Redirect || response.StatusCode == System.Net.HttpStatusCode.Moved)
{
return response.Headers.Location.AbsoluteUri;
}
return url;
}