How to send file with HttpClient post in xamarin forms

amr_kamalamr_kamal Member ✭✭✭

I want to send file through post request using httpclient this what i tried but file didn't sent , when i tried in postman it works fine

string Url = $"http://ataprojects.net/test/products.php?request_type=add&company_name={BaseService.Company}&name={product.name}&barcode={product.barcode}&buy_price={product.buy_price}&sell_price={product.sell_price}";
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    var content = new MultipartFormDataContent();
                    content.Headers.ContentType.MediaType = "multipart/form-data";
                    content.Add(new StreamContent(product._mediaFile.GetStream()),
                      "image",
                       product.image);                    
                    var response = client.PostAsync(Url, content).Result;

                    response.EnsureSuccessStatusCode();
                    if (response.IsSuccessStatusCode)
                    {
                        var contentdata = await response.Content.ReadAsStringAsync();                       
                        var Items = JsonConvert.DeserializeObject<AddProductReturnModel>(contentdata);
                        return Items;
                    }
                    else
                    {
                        return null;
                    }
                }

            }

what's the problem ?

Best Answer

Answers

  • RylaRyla Member ✭✭

    try this
    ` public async static Task CheckDevice()
    {

            string res = "";
            if (CrossConnectivity.Current.IsConnected == true){
                try
                {
                HttpClient client = new HttpClient();
                client.BaseAddress = "YOUR APİ;
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("aplication/json"));
                client.DefaultRequestHeaders.Add("DeviceCode",DeviceId);
                client.DefaultRequestHeaders.Add("Secret", Config.Secret);
                HttpResponseMessage response = await client.GetAsync("YOUR APİ);
                if (response.IsSuccessStatusCode)
                    {
                    res =  response.Content.ReadAsStringAsync().Result;
    
                }
                    else
                    {
                    //  res = "Err:" + await response.Content.ReadAsStringAsync();
                    res = null;
                    }
                }
                catch (Exception ex)
                {
                    res = "Err:" + ex.Message;
                }
            }
            else
            {
    
                await Application.Current.MainPage.DisplayAlert("Warning!", "no Internet connection", "ok");
                if (DeviceInfo.Platform == Device.Android)
                {
                    Thread.CurrentThread.Abort();
                }
                else if (DeviceInfo.Platform == Device.iOS)
                {
                    Thread.CurrentThread.Abort();
                }
            }
            return res;
        }`
    
  • amr_kamalamr_kamal Member ✭✭✭

    @Ryla It's post request with file , sample like what i did in postman
    i followed this link

    https://github.com/HoussemDellai/UploadFileToServer

    but doesn't work for me in mobile side

  • amr_kamalamr_kamal Member ✭✭✭
    Accepted Answer

    I Solved it by changing the key like in postman "image"

  • Mayank.0569Mayank.0569 USMember ✭✭

    using System;
    using System.Diagnostics;
    using System.Threading.Tasks;
    using Newtonsoft.Json;
    using SQLiteDemoWithRestService.Library.Common;

    namespace SQLiteDemoWithRestService.Library.ServiceCenter.Request
    {
    public class HttpRequestHelper
    {
    protected readonly string ServiceEndpoint;

        public HttpRequestHelper()
        {
            ServiceEndpoint = Constants.BASE_URL;
        }
    
    
        public async Task<T> CreateGetResponse<T>(string ServiceAPIResourcePath, string accessToken = null, string deviceId = null)
        {
            try
            {
    
                var httpBaseClient = new HttpBaseClient(System.IO.Path.Combine(new string[] {
                    ServiceEndpoint,
                    ServiceAPIResourcePath
                }), accessToken, deviceId);
    
                var responseCRServiceContent = await httpBaseClient.Get();
                return ServiceHelper.GetResponse<T>(responseCRServiceContent);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                throw;
            }
        }
    
        public async Task<T> CreatePostRequest<T>(string ServiceAPIResourcePath, object payload, string accessToken = null)
        {
            var httpBaseClient = new HttpBaseClient(System.IO.Path.Combine(new string[] {
                ServiceEndpoint,
                ServiceAPIResourcePath
            }), accessToken);
            if (payload.GetType().ToString() != "System.String")
            {
                payload = JsonConvert.SerializeObject(payload);
            }
            var responseServiceContent = await httpBaseClient.Post(payload.ToString());
            return ServiceHelper.GetResponse<T>(responseServiceContent);
        }
    
        public async Task<T> CreatePostRequestWithoutToken<T>(string ServiceAPIResourcePath, string payload, string accessToken = null)
        {
            try
            {
                var httpBaseClient = new HttpBaseClient(System.IO.Path.Combine(new string[] {
                ServiceEndpoint,
                ServiceAPIResourcePath
            }));
                var responseServiceContent = await httpBaseClient.Post(payload.ToString());
                return ServiceHelper.GetResponse<T>(responseServiceContent);
            }
            catch (Exception ex)
            {
                return default(T);
            }
        }
    
    
        public async Task<T> CreatePutRequest<T>(string ServiceAPIResourcePath, object payload, string accessToken = null)
        {
            var httpBaseClient = new HttpBaseClient(System.IO.Path.Combine(new string[] {
                ServiceEndpoint,
                ServiceAPIResourcePath
            }), accessToken);
            if (payload.GetType().ToString() != "System.String")
            {
                payload = JsonConvert.SerializeObject(payload);
            }
            var responseServiceContent = await httpBaseClient.Put(payload.ToString());
            return ServiceHelper.GetResponse<T>(responseServiceContent);
        }
    
        public async Task<T> CreateDeleteRequest<T>(string ServiceAPIResourcePath, string accessToken = null)
        {
            try
            {
                var httpBaseClient = new HttpBaseClient(System.IO.Path.Combine(new string[] {
                    ServiceEndpoint,
                    ServiceAPIResourcePath
                }), accessToken);
    
                var responseCRServiceContent = await httpBaseClient.Delete();
                return ServiceHelper.GetResponse<T>(responseCRServiceContent);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                throw;
            }
        }
    
    }
    

    }

  • Mayank.0569Mayank.0569 USMember ✭✭

    public class HttpBaseClient
    {
    protected readonly string Endpoint;
    protected readonly string AccessToken;
    protected readonly string DeviceId;
    HttpClient httpClient;

        public HttpBaseClient(string endpoint, string accessToken = null, string deviceId = null)
        {
            Endpoint = endpoint;
            httpClient = new HttpClient();
            AccessToken = accessToken;
            DeviceId = deviceId;
        }
    
        private void SetHeader(bool isFileUpload = false)
        {
            if (isFileUpload)
            {
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/form-data"));
            }
            else
            {
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            }
            if (!string.IsNullOrWhiteSpace(AccessToken))
            {
                httpClient.DefaultRequestHeaders.Add("token", AccessToken);
            }
        }
    
        public async Task<string> Get()
        {
            string response;
            try
            {
                this.SetHeader();
                response = await this.httpClient.GetStringAsync(Endpoint);
            }
            catch (UnauthorizedAccessException ex)
            {
                response = BuildErrorMessage(ex);
            }
            catch (TaskCanceledException exception)
            {
                response = BuildErrorMessage(exception);
            }
            catch (HttpRequestException exception)
            {
                response = BuildErrorMessage(exception);
            }
            catch (Exception exception)
            {
                response = BuildErrorMessage(exception);
            }
            finally
            {
                httpClient.Dispose();
            }
            response = response
                        .Trim('"')
                        .Replace(@"\", "");
    
            return response;
        }
    
        public async Task<string> Put(string payload)
        {
            HttpResponseMessage responseMessage;
            string result = null;
    
            try
            {
                this.SetHeader();
    
                responseMessage = await this.httpClient.PutAsync(Endpoint, new StringContent(payload, System.Text.Encoding.UTF8, "application/json"));
    
                result = await responseMessage.Content.ReadAsStringAsync();
    
            }
            catch (UnauthorizedAccessException ex)
            {
                result = BuildErrorMessage(ex);
            }
            catch (TaskCanceledException exception)
            {
                result = BuildErrorMessage(exception);
            }
            catch (HttpRequestException exception)
            {
                result = BuildErrorMessage(exception);
            }
            catch (Exception exception)
            {
                result = BuildErrorMessage(exception);
            }
            finally
            {
                httpClient.Dispose();
            }
    
            return result;
        }
    
        public async Task<string> Post(string payload)
        {
            HttpResponseMessage responseMessage;
            string result = null;
            try
            {
                HttpClient httpClient1 = new HttpClient();
                if (Constants.DevicePlatform == "iOS")
                {
                    httpClient1 = new HttpClient(new NativeMessageHandler(throwOnCaptiveNetwork: false, customSSLVerification: true));
                }
    
                   this.SetHeader();
                SSLCheck.Initialize();
                responseMessage = await httpClient1.PostAsync(Endpoint, new StringContent(payload, System.Text.Encoding.UTF8, "application/json"));
    
           //     responseMessage = await httpClient.PostAsync(Endpoint, new StringContent(payload, System.Text.Encoding.UTF8, "application/json"));
                result = await responseMessage.Content.ReadAsStringAsync();
            }
            catch (UnauthorizedAccessException ex)
            {
                result = BuildErrorMessage(ex);
            }
            catch (TaskCanceledException ex)
            {
                result = BuildErrorMessage(ex);
            }
            catch (HttpRequestException ex)
            {
                result = BuildErrorMessage(ex);
            }
            catch (Exception ex)
            {
                result = BuildErrorMessage(ex);
            }
            finally
            {
                httpClient.Dispose();
            }
            if (result == "0")
                result = true.ToString();
            return result;
        }
    
        public async Task<string> Delete()
        {
            HttpResponseMessage responseMessage;
            string result = null;
    
            try
            {
                this.SetHeader();
    
                responseMessage = await this.httpClient.DeleteAsync(Endpoint);
    
                result = await responseMessage.Content.ReadAsStringAsync();
    
            }
            catch (TaskCanceledException exception)
            {
                result = BuildErrorMessage(exception);
            }
            catch (HttpRequestException exception)
            {
                result = BuildErrorMessage(exception);
            }
            catch (Exception exception)
            {
                result = BuildErrorMessage(exception);
            }
            finally
            {
                httpClient.Dispose();
            }
    
            return result;
        }
    
        public string BuildErrorMessage(Exception ex)
        {
            ErrorMessage msg;
            if (ex == null)
            {
                msg = new ErrorMessage()
                {
                    Message = "Constants.ErrorInServiceMessage"
                };
            }
            else
            {
                if (ex.Equals(ex as OperationCanceledException))
                {
                    msg = new ErrorMessage()
                    {
                        Message = ex.Message.Equals("A task was canceled.") ? Constants.ServerNotResponding : string.Empty
                    };
                }
                else if (ex.Equals(ex as UnauthorizedAccessException))
                {
                    msg = new ErrorMessage()
                    {
                        Message = "Licence invalid"
                    };
                }
                else
                    msg = new ErrorMessage()
                    {
                        Message = ex.Message
                    };
            }
            return JsonConvert.SerializeObject(msg);
        }
    }
    
Sign In or Register to comment.