Xamarin Form not able to invoke the Http URL - xamarin.forms

I am new to Xamarin Cross-Flatform technology (C#). I am developing one small application where I need to call the http url, get the json data, parse it and display it on the screen.
I am using System.Net.Http for achieving the http call.But request is not reaching to http url
Regards,
Amit Joshi

You can use RestSharp for making http calls.
It is very easy to use.
Code sample:
using RestSharp;
var client = new RestClient ("http://rxnav.nlm.nih.gov/REST/RxTerms/rxcui/");
var request = new RestRequest (String.Format ("{0}/allinfo", "198440"));
client.ExecuteAsync (request, response => {
Console.WriteLine (response.Content);
});
RestSharp Examples

Related

Get the raw request that is sent with HttpClient and HttpRequestMessage

In my C# code running .NET 6 (Azure Function) I am sending an HttpRequestMessage using HttpClient. It doesn't work but it should work, so I want to get the raw request that I am sending, including the header, so I can compare with the documentation and see the differences.
In the past I have used Fiddler but it doesn't work for me now, probably because of some security settings on my laptop. So I am looking for a solution within the world of Visual Studio 2022 or .NET 6 where I can get the raw request out for troubleshooting purposes.
This question is not really about code, but here is my code anyway.
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://myendpoint.com/rest/something");
var apiToken = "AOU9FrasdgasdfagtHJNV";
request.Headers.Add("Authorization", "Basic " + apiToken);
var message = new
{
sender = "Hey",
message = "Hello world",
recipients = new[] { new { id = 12345678} }
};
request.Content = new StringContent(JsonSerializer.Serialize(message), Encoding.UTF8, "application/json");
request.Headers.Add("Accept", "application/json, text/javascript");
HttpResponseMessage response = await httpClient.SendAsync(request);
When SendAsync is invoked, I wish to know what exactly is sent, both header and content.
If you cannot use any proxy solution (like Fiddler) then I can see 2 options. One is described in comments in your question to use DelegatingHandler. You can read more about this in documentation. What is interesting is that HttpClient supports logging out of the box which is described in this section https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-6.0#logging of the article which describes DelegatingHandlers
If you are worried that something will manipulate the outgoing request then you can implement option 2. This is to create temporary asp.net core application with .UseHttpLogging() middleware plugged in into pipeline as described here https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-logging/?view=aspnetcore-6.0 That way you will know exactly how your request looks like from application which is being requested point of view. Now if you will point your azure function to you temporary app - you should see what gets send
Hope it helps

How to add Bearer token to Simple OData Client

New to OData, I need to access SAP Odata Web Service that required Authentication and Token. Say I have the token hardcoded. How to add this token to Simple OData Client?
var settings = new Simple.OData.Client.ODataClientSettings();
settings.BaseUri = new Uri("https://..../UoM?$filter=wer eg '1000' &format=json");
settings.Credentials = new NetworkCredential("user1", "usrpwd");
var client = new ODataClient(settings);
Please kindly help me.
Update --
In this link : Simple Odata Client - How to add oAuth Token in each request header?
It didnot show how to add the hardcoded Token. For my problem, I need to add a given token and make a Odata Request. I check the Odata.org website, I dont seems to find any example for my case.
I have no experience on simple.Odata.client, Can some1 be kind enough to show me how.
Thanks
I believe you can use the ODataClientSettings.BeforeRequest action to alter the request before it is sent.
In the example below I set the Authorization header of the request to 'Bearer <Token>':
settings.BeforeRequest = req => {
req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "Your_Token_Here");
};
Of course it is up to you to configure the request for you specific type of authentication.
The URL you use in your example is clearly wrong and not the OData URL for SAP.
You need the base URL for the "yourODataServiceRootURL" below and then add the relative path later in the ODataclient setting eg. "api/data/v9.1"
Instead of using the delegate method to intercept and add the Authorization header on every Http call, a clearer/cleaner solution is to instantiate the ODataClient with an HttpClient instance.
This also allows you to control the HttpClient lifecycle externally.
The code below is an extract of a .Net core app using an Azure AD OAuth2 token to connect to a Dynamics 365 OData Web API.
httpClient.BaseAddress = new Uri(yourODataServiceRootURL);
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", yourBearerAccessToken);
//Use the httpClient we setup with the Bearer token header
var odataSettings = new ODataClientSettings(httpClient, new Uri("api/data/v9.1", UriKind.Relative));
var odataClient = new ODataClient(odataSettings);

Do I need to do something special in the ASP.NET MVC app to read a Json response from a Web API 2 application?

Is there something special I need to define in an ASP.NET MVC application to read an incoming response from a ASP.NET Web API?
From my MVC app, I make a request to an ASP.NET Web API using System.Net.HttpClient. The API receives the request and processes it fine and returns a valid response. However, the MVC application, it appears, never gets the response. I have a break point on the line that makes the request. The flow of control never comes back after executing that line. The MVC app just keeps waiting and times-out after a very long time.
However, I can confirm that the API returns a valid Json response. I have tried composing this request in Chrome Postman and see that the API returns a valid response.
Here's the code from my MVC app that makes the request to the Web API:
public async Task<R> PostAsJsonAsync<T, R>(string uri, T value)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(_baseUri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PostAsJsonAsync(uri, value);
if (response.IsSuccessStatusCode) return await response.Content.ReadAsAsync<R>();
else return default(R);
}
}
In the past, i.e. before Web API 2, I've had MVC apps talk to the Web API without any problem. I don't know if I am missing something that has been introduced in Web API 2.
I have a feeling you are getting a deadlock. Are you using .Result anywhere? You should be using async all the way. I mean your MVC action method should also be async method and they should await and not use .Result. Read this log post by Stephen Cleary for more info. http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html

Calling an API inside an ASP.net MVC Controller Action

I am developing an asp.net mvc web application in which I need to call OMDB api (an api to get Imdb information of a movie). I need to send a simple GET request to the api and get the response(movie details), deserialize the response into an object and pass it to the view. Is this possible without using a reference to an external library? Can anybody give me an example on how to do it inside a controller action.
You can use the WebRequest class
using System.Net;
string url = "https://www.service.com?param=movieName";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
Reference:
http://support.microsoft.com/kb/307023

how can i invoke facebook http rest api whitout facebook api lib's (java or C++)

i like to preform simple facebook api call via http rest
but whiteout using facebook java/c++ pre made lib
plain http call
i already done the authorization part and i have the session id and all that .
i just like to see what i need to preform api call over http
thanks
Just use the Facebook Rest API to create your URLs and then send the response via POST
from http://www.exampledepot.com/egs/java.net/Post.html
URL url = new URL("http://hostname:80/cgi");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();

Resources