Beispiel #1
0
    protected override void OnSuccess()
    {
        onSuccess?.Invoke();

        /*
         * if (onSuccess != null)
         *      onSuccess.Invoke(); // onSuccess();
         *
         */
    }
Beispiel #2
0
 protected override void OnSuccess()
 {
     onSuccess?.Invoke();
 }
Beispiel #3
0
        /// <summary>
        ///     Makes a request and deserializes the result JSON as T class objects.
        ///     Check https://forums.xamarin.com/discussion/22732/3-pcl-rest-functions-post-get-multipart
        /// </summary>
        /// <param name="method">The http method can be "GET", "POST", "PUT" or "DELETE"</param>
        /// <param name="endpoint">The endpoint name i.e. "/api/v1/feed"</param>
        /// <param name="body">If the method is GET, the query string URI to set in the URL. Otherwise the json body.</param>
        /// <param name="authToken">The AUTH_TOKEN cookie.</param>
        private async Task MakeRequest(string method, string endpoint, string body, string authToken = null)
        {
#if DEBUG
            Debug.WriteLine("Hitting: " + endpoint);
            Debug.WriteLine("Body payload: " + body);
#endif

            RequestStartedHandler?.Invoke();
            if (!CrossConnectivity.Current.IsConnected)
            {
                HandleNoConnectivity();
                return;
            }

            try
            {
                //If the method is GET we've to concat the query string uri, i.e. "/feeds" + "?id=something"
                if (method.Equals(HttpMethod.Get.Method) && !string.IsNullOrEmpty(body))
                {
                    endpoint += body;
                }
                var request = (HttpWebRequest)WebRequest.Create(new Uri(endpoint));
                SetHeaders(request);
                request.Method = method;
                if (!string.IsNullOrEmpty(authToken))
                {
                    request.Headers["Cookie"] = authToken;
                }

                if (method.Equals(HttpMethod.Post.Method) || method.Equals(HttpMethod.Put.Method))
                {
                    if (!string.IsNullOrEmpty(body))
                    {
                        var requestStream = await request.GetRequestStreamAsync();

                        using (var writer = new StreamWriter(requestStream))
                        {
                            writer.Write(body);
                            writer.Flush();
                            writer.Dispose();
                        }
                    }

                    if (string.IsNullOrWhiteSpace(_filePath) == false && File.Exists(_filePath))
                    {
                        //  Post Multi-part data
                        var fileStream = File.Open(_filePath, FileMode.Open, FileAccess.Read);
                        //  Expected
                        //  Header
                        //  Content-Length: 18101
                        //  Content-Type: multipart/form-data; boundary = ---------------------------13455211745882
                        //  Cookie: AUTH-TOKEN=eyJhbGciOiJIUz
                        //  Body
                        //  -----------------------------13455211745882
                        //  Content-Disposition: form-data; name="file"; filename="Feed List View.png"
                        //  Content-Type: image/png
                        //  Byte body
                        //  -----------------------------13455211745882--

                        var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");

                        request.ContentType = "multipart/form-data; boundary=" + boundary;

                        request.Credentials = CredentialCache.DefaultCredentials;

                        var requestStream = await request.GetRequestStreamAsync();

                        var headerTemplate =
                            "--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n";

                        var header = string.Format(headerTemplate, boundary, _fileParameterName, _fileName,
                                                   _fileContentType);

                        Debug.WriteLine(header);

                        var headerbytes = Encoding.UTF8.GetBytes(header);

                        using (var requestStreamWriter = new BinaryWriter(requestStream))
                        {
                            requestStreamWriter.Write(headerbytes, 0, headerbytes.Length);

                            var fileByteStream = ReadFully(fileStream);
                            Debug.WriteLine("Bytes read:" + fileByteStream.Length);
                            requestStreamWriter.Write(fileByteStream, 0, fileByteStream.Length);

                            var trailer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--");
                            requestStreamWriter.Write(trailer, 0, trailer.Length);

                            Debug.WriteLine("(Using) Request ContentType: " + request.ContentType);
                        }
                    }
                }

                Debug.WriteLine("Request ContentType: " + request.ContentType);

                var response = (HttpWebResponse)await request.GetResponseAsync();

                Debug.WriteLine("Response Content-Lenght: " + response.ContentLength);

                HeaderResultHandler?.Invoke(response.Headers);
                var respStream = response.GetResponseStream();

                using (var sr = new StreamReader(respStream))
                {
                    //Need to return this response
                    var stringResponse = sr.ReadToEnd();
                    Debug.WriteLine("Json response: " + stringResponse);
                    var result = JsonConvert.DeserializeObject <T>(stringResponse);
                    SuccessHandler?.Invoke(result);
                    RequestCompletedHandler?.Invoke();
                }
            }
            catch (WebException e)
            {
                if (e.Response == null)
                {
                    HandleUnknownError(new Exception("Null response"));
                    return;
                }

#if DEBUG
                using (var stream = e.Response.GetResponseStream())
                    using (var reader = new StreamReader(stream))
                    {
                        Debug.WriteLine("Server-side error:" + reader.ReadToEnd());
                    }
#endif
                HandleWebExceptionError(e);
            }
            catch (JsonSerializationException e)
            {
                HandleJsonError(e);
            }
            catch (Exception e)
            {
                HandleUnknownError(e);
            }
        }