Search code examples
httppostgetxamarinmvvmcross

Xamarin MvvmCross Http Request : How does this work?


I try to get and send data via HTTP requests. example: HTTP GET (with Headers), to retrieve Headers and Body HTTP POST (with Headers and Body), to retrieve Headers and Body I need to manipulate Headers and Body, using MvvmCross (an implementation of Mvvm for Xamarin)

For a first version, I had developed:

public static class Http
{

    public static async Task<HttpResponseMessage> Get (string url)
    {
        using(var httpClient = new HttpClient ()) {
            HttpRequestMessage request = new HttpRequestMessage (HttpMethod.Get, SharedResources.Api.ServerAddress + url);
            request.Headers.Add ("Content-Type", "application/json");
            var response = await httpClient.SendAsync (request);
            return response;
        }
    }

    public static async Task<HttpResponseMessage> Post (string url, string body = "", string contentType = "application/json")
    {
        using (var httpClient = new HttpClient ()) {
            httpClient.DefaultRequestHeaders.Accept.Add (new MediaTypeWithQualityHeaderValue (contentType));
            var response = await httpClient.PostAsync (SharedResources.Api.ServerAddress + url, new StringContent(body));
            return response;
        }
    }
}

For second version, I’ve develop that, but I don’t know how to get responseString

public static async Task<IAsyncResult> Post (string url, Dictionary<string,string> customHeaders, string body = "", string contentType = "application/json")
    {
        String finalresult = String.Empty;
        HttpWebRequest httpPostWebRequest = (HttpWebRequest)WebRequest.Create (SharedResources.Api.ServerAddress + url);
        foreach (var header in customHeaders) {
            httpPostWebRequest.Headers [header.Key] = header.Value;
        }
        Task.Factory.StartNew (() => {

            httpPostWebRequest.ContentType = contentType;
            httpPostWebRequest.Method = "POST";
            return httpPostWebRequest.BeginGetRequestStream ((requestStreamAsyncResult) => {
                HttpWebRequest httpWebRequestStream = (HttpWebRequest)requestStreamAsyncResult.AsyncState;
                Stream postStream = httpWebRequestStream.EndGetRequestStream (requestStreamAsyncResult);
                byte[] byteArray = Encoding.UTF8.GetBytes (body);
                postStream.Write (byteArray, 0, body.Length);
                httpWebRequestStream.BeginGetResponse ((responseAsyncResult) => {
                    HttpWebRequest request = (HttpWebRequest)responseAsyncResult.AsyncState;
                    HttpWebResponse response = (HttpWebResponse)request.EndGetResponse (responseAsyncResult);
                    Stream streamResponse = response.GetResponseStream ();
                    StreamReader streamRead = new StreamReader (streamResponse);
                    string responseString = streamRead.ReadToEnd ();
                    //**need to return responseString content**
                }, httpWebRequestStream);
            }, httpPostWebRequest);

        });
    }

Now, I’ve found this blog entry : http://blogs.msdn.com/b/bclteam/archive/2013/02/18/portable-httpclient-for-net-framework-and-windows-phone.aspx

and write this code :

public async static Task<String> Post (string url, Dictionary<string, string> headers = null, string body = "", string contentType = "application/json")
    {

        HttpClientHandler handler = new HttpClientHandler ();
        var httpClient = new HttpClient (handler);
        HttpRequestMessage request = new HttpRequestMessage (HttpMethod.Post, SharedResources.Api.ServerAddress + url);

        if (headers != null) {
            foreach (var header in headers) {
                request.Headers.Add (header.Key, header.Value);
                Mvx.Trace ("Adding {0} header to request, value {1} OK", header.Key, header.Value);

                httpClient.DefaultRequestHeaders.Add (header.Key, header.Value);
                Mvx.Trace ("Adding {0} header to httpClient, value {1} OK", header.Key, header.Value);
            }
        }

        request.Content = new StringContent (body, Encoding.UTF8, contentType);
        Mvx.Trace ("Adding content {0}", await request.Content.ReadAsStringAsync());

        if (handler.SupportsTransferEncodingChunked ()) {
            //REQUEST
            request.Headers.TransferEncodingChunked = true;

            // HTTPCLIENT
            httpClient.DefaultRequestHeaders.TransferEncodingChunked = true;
        }

        Mvx.Trace ("READING request.Headers CONTENT");
        foreach (var header in request.Headers) {
            foreach (var value in header.Value) {
                Mvx.Trace ("{0} : {1}", header.Key, value);
            }
        }

        Mvx.Trace ("READING httpClient.DefaultRequestHeaders CONTENT");
        foreach (var header in httpClient.DefaultRequestHeaders) {
            foreach (var value in header.Value) {
                Mvx.Trace ("{0} : {1}", header.Key, value);
            }
        }

        HttpResponseMessage response = await httpClient.SendAsync (request);
        Mvx.Trace ("SendAsync response : {0}", response.ToString ());

        return await response.Content.ReadAsStringAsync ();
    }

Solution

  • I’ve found the solution ! :D

        public async static Task<String> Post (string url, Dictionary<string, string> headers = null, string body = "", string contentType = "application/json")
        {
            HttpClientHandler handler = new HttpClientHandler ();
            var httpClient = new HttpClient (handler);
            HttpRequestMessage request = new HttpRequestMessage (HttpMethod.Post, SharedResources.Api.ServerAddress + url);
    
            // add headers
            if (headers != null) {
                foreach (var header in headers) {
                    request.Headers.Add (header.Key, header.Value);
                    httpClient.DefaultRequestHeaders.Add (header.Key, header.Value);
                }
            }
            // set the content
            request.Content = new StringContent (body, Encoding.UTF8, contentType);
            // set the content length
            request.Content.Headers.ContentLength = body.Length;
    
            // set transfer-enconding 
            if (handler.SupportsTransferEncodingChunked ()) {
                bool chuncked = false;
                request.Headers.TransferEncodingChunked = chuncked;
                httpClient.DefaultRequestHeaders.TransferEncodingChunked = chuncked;
            }
            // await and return response
            HttpResponseMessage response = await httpClient.SendAsync (request);
            return await response.Content.ReadAsStringAsync ();
        }