0

Is it possible to perform an HTTP request and get the response body in Xamarin? because i tried many code examples from their documentation and it does not work on my Android device, there's an exception that says: NameResolutionFailure.

My code is:

        Uri uri = new Uri("http://www.google.com");
        string ret = "ERROR";
        try
        {
            using (WebClient webClient = new WebClient())
            {
                //You can set webClient.Headers there
                webClient.Encoding = System.Text.Encoding.UTF8;
                ret = webClient.DownloadString(uri);
                Console.WriteLine("Data: " + ret);
            }
        }
        catch (Exception ex)
        {
            ret = ex.Message;
            Console.WriteLine("Error: " + ret);
        }

I found out that this error occures when you're doing the request through WIFI, but seriousely?

All the dirty solutions like "replace the hostname by the IP address" don't work, i'm new to Xamarin and i have a bad impression on it.

4 R4C81D
  • 192
  • 13

1 Answers1

0

I am writing a simple example to how to fetch data using Newtonsoft.Json:

public static async Task<Details> getDetails(string authKey, string AppVersionandBuild)
{

    var response = await JsonWebCall<Details>.GetDirect(
       JsonWebCall<object>.baseURl + "MyApp/GetDetails",
       authKey,
       AppVersionandBuild);

    return response.Item1;
}

And this is my JsonWebCall Class

    public class JsonWebCall<T>
{
    public static string baseURl = "http://YourServiceURL/";

     /// <summary>
     /// Gets the client.
     /// </summary>
     /// <returns></returns>
    public static HttpClient GetClient()
    {
        var timeout = new TimeSpan(0, 10, 0);
        var client = new HttpClient(new ModernHttpClient.NativeMessageHandler() );
        // Due to a bug in Xamarin's HttpClient, this value MUST exceed the timeout of the native http client.  
        // The REAL timeout will be the native http client's timeout which will properly throw the timeout exception.
        client.Timeout = timeout.Add(new TimeSpan(0, 1, 0));
        return client;
    }

    /// <summary>
    /// Gets the message.
    /// </summary>
    /// <param name="method">The method.</param>
    /// <param name="url">The URL.</param>
    /// <param name="authkey">The authkey.</param>
    /// <param name="Manufacturer">The manufacturer.</param>
    /// <param name="Model">The model.</param>
    /// <param name="OS">The os.</param>
    /// <param name="OSVersion">The os version.</param>
    /// <param name="UniqueIdentifier">The unique identifier.</param>
    /// <param name="AppVersionandBuild">The application versionand build.</param>
    /// <returns></returns>
    public static HttpRequestMessage GetMessage(HttpMethod method, string url, string authkey, string Manufacturer, string Model, string OS, string OSVersion, string UniqueIdentifier, string AppVersionandBuild)
    {
        var message = new HttpRequestMessage(method, url);

        if (!string.IsNullOrWhiteSpace(authkey))
            message.Headers.Add("X-AUTH-KEY", new List<string>() { authkey });
        if (!string.IsNullOrWhiteSpace(UniqueIdentifier))
            message.Headers.Add("X-DEVICE-ID", new List<string>() { UniqueIdentifier });
        if (!string.IsNullOrWhiteSpace(Model))
            message.Headers.Add("X-DEVICE-MODEL", new List<string>() { Model });
        if (!string.IsNullOrWhiteSpace(Manufacturer))
            message.Headers.Add("X-DEVICE-MFG", new List<string>() { Manufacturer });
        if (!string.IsNullOrWhiteSpace(OSVersion))
            message.Headers.Add("X-OS-VERSION", new List<string>() { OSVersion });
        if (!string.IsNullOrWhiteSpace(OS))
            message.Headers.Add("X-OS-NAME", new List<string>() { OS });
        if (!string.IsNullOrWhiteSpace(AppVersionandBuild))
            message.Headers.Add("X-APP-VERSION", new List<string>() { AppVersionandBuild });
        return message;
    }
    /// <summary>
    /// Get data that is not encapulated in an odata call
    /// </summary>
    /// <param name="url">the url of the service action</param>
    /// <param name="authkey">The authentication key required y the server</param>
    /// <param name="DeviceID">the device id of the device making this service call</param>
    /// <returns></returns>
    public async static Task<Tuple<T>> Get(string url, string authKey, string Manufacturer, string Model, string OS, string OSVersion, string UniqueIdentifier, string AppVersionandBuild)
    {
        var client = GetClient();
        var req = GetMessage(HttpMethod.Get, url, authKey, Manufacturer, Model, OS, OSVersion, UniqueIdentifier, AppVersionandBuild);
        var response = await client.SendAsync(req).ConfigureAwait(false);
        T returnedObject = default(T);
        returnedObject = JsonConvert.DeserializeObject<T>(await response.Content.ReadAsStringAsync().ConfigureAwait(false));

        return new Tuple<T>(returnedObject);
    }
    /// <summary>
    /// Gets the request.
    /// </summary>
    /// <param name="method">The method.</param>
    /// <param name="url">The URL.</param>
    /// <param name="authkey">The authkey.</param>
    /// <param name="AppVersionandBuild">The application versionand build.</param>
    /// <returns></returns>
    public static HttpRequestMessage GetRequest(HttpMethod method, string url, string authkey, string AppVersionandBuild)
    {
        var message = new HttpRequestMessage(method, url);

        if (!string.IsNullOrWhiteSpace(authkey))
            message.Headers.Add("X-AUTH-KEY", new List<string>() { authkey });
        if (!string.IsNullOrWhiteSpace(AppVersionandBuild))
            message.Headers.Add("X-APP-VERSION", new List<string>() { AppVersionandBuild });
        return message;
    }

    /// <summary>
    /// Gets the direct.
    /// </summary>
    /// <param name="url">The URL.</param>
    /// <param name="authKey">The authentication key.</param>
    /// <param name="AppVersionandBuild">The application versionand build.</param>
    /// <returns></returns>
    public async static Task<Tuple<T>> GetDirect(string url, string authKey, string AppVersionandBuild)
    {
        var client = GetClient();
        var req = GetRequest(HttpMethod.Get, url, authKey, AppVersionandBuild);
        var response = await client.SendAsync(req).ConfigureAwait(false);
        T returnedObject = default(T);
        var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
        returnedObject = JsonConvert.DeserializeObject<T>(result);
        return new Tuple<T>(returnedObject);
    }   
}
Naveen Gogineni
  • 306
  • 2
  • 11
  • I'm gonna try it and get back to you, Thanks, btw how and should i import Newtonsoft.Json in Visual Studio? – 4 R4C81D May 31 '17 at 04:26
  • btw what is AppVersionandBuild and authKey? why is it so much complicated to do a simple HTTP request? – 4 R4C81D May 31 '17 at 04:39
  • 1
    Those are mandatory where if you upgrade to a new version then you might have to support your users who are using old version. In that case you have to pass app version, build, etc., to make your requests unique based on the version user using. – Naveen Gogineni May 31 '17 at 04:48
  • ModernHttpClient is not recognized, what should i do right there? – 4 R4C81D May 31 '17 at 05:02
  • Download Nuget Package for ModrenHttpClient – Naveen Gogineni May 31 '17 at 05:03
  • Ok, thanks, also T type wasn't recognized so i replaced it with String, is that okay? Thanks for keeping up... – 4 R4C81D May 31 '17 at 05:05
  • 1
    Its ok, But try reading about [Generic Type Parameter](https://stackoverflow.com/a/9857185/8063119). – Naveen Gogineni May 31 '17 at 05:18
  • It looks like this is working, only that i cannot get the response because it timesout, i'll try to figure out how to properly call async method in a thread or something (I'm new to this whole .NET mess, this is my HelloWorld, i came from Java). Thank you. – 4 R4C81D May 31 '17 at 06:09