How do i consume a ASMX services in Android?

Jonathan0931Jonathan0931 Member ✭✭
edited June 2018 in Xamarin.Forms

Hi,

I have a ASMX service and works fine, but when i try to call it from the code ater a few seconds return Time Out, i try to increase the time out value but aswer me the same,

the steps i made for calling the web service are:

Add the referense to Web Service

Create an instance of WS
var serv = new ServicioSync.WebService2();

And call the method i need
string Respuesta = "";
Respuesta = serv.Envia(dataSet);
return Respuesta;

this is in a native android class

i dont know what to do please help!

Thanks!

Answers

  • SirAndriySirAndriy USMember ✭✭✭
    What about accessing to internet connection?
  • Jonathan0931Jonathan0931 Member ✭✭

    thanks for answer, yes i have access to internet and the android manifest have the permition

  • WashingtonMoraisWashingtonMorais USMember ✭✭

    hum.... thats why I always use a RestService.
    See below a sniped

    In your PCL project

        // Using declarations
        ...
        using Newtonsoft.Json;
        using System.Net.Http;
        using System.Net.Http.Headers;
        ...
    
    
        // User Class Model
        public class UserModel
        {
          public string Login {get;set;}
          public string Password {get;set;}
        }
    
        // Response Object 
        public class BaseResponse
        {
          public bool Success {get;set;}
          public string Message {get;set;}
          public object Model {get;set;}
        }
    
    public async Task<BaseResponse> LoginUsuarioAsync(UserModel user)
    {
        var baseResponse = new BaseResponse();
        try
        {
            var httpClient = new HttpClient(new HttpClientHandler { AutomaticDecompression = System.Net.DecompressionMethods.GZip });
            httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
            httpClient.MaxResponseContentBufferSize = 5000000;
            httpClient.Timeout = TimeSpan.FromSeconds(15);
    
            // To use Auth Token 
            // httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "TOKEN STRING");
    
            var serializedModel = JsonConvert.SerializeObject(user);
            var content = new StringContent(serializedModel, Encoding.UTF8, "application/json");
            var response = await httpClient.PostAsync("http://server/api/loginuser", content);
    
            // Check results
            if (response != null && response.IsSuccessStatusCode)
            {
                string responseString = null;
                using (var stream = await response.Content.ReadAsStreamAsync())
                using (var reader = new System.IO.StreamReader(stream))
                    responseString = reader.ReadToEnd();
    
                if (string.IsNullOrEmpty(responseString))
                {
                    return new BaseResponse(false, 'handle error');
                }
    
                dynamic userModel = Newtonsoft.Json.Linq.JObject.Parse(responseString);
    
                if (userModel != null)
                {
                    Dictionary<string, object> props = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseString);
                    BaseResponse respTemp = JsonConvert.DeserializeObject<BaseResponse>(Convert.ToString(userModel));
    
                    if (respTemp.Success)
                    {
                        UserModel model = JsonConvert.DeserializeObject<UserModel>(Convert.ToString(props["Model"].ToString()));
                        if (model != null && !string.IsNullOrEmpty(model.Login))
                        {
                            baseResponse.Model = model;
                            baseResponse.Success = true;
                        }
                    }
                    else
                    {
                        baseResponse.Success = false;
                        baseResponse.Message = respTemp.Message;
                    }
                }
                else
                {
                    return new BaseResponse(false, "Generic error");
                }
            }
            else
            {
                return new BaseResponse(false, "Generic error");
            }
        }
        catch (Exception ex)
        {
            baseResponse.Success = false;
            baseResponse.Message = ex.Message;
        }
    
        return baseResponse;
    }
    

    In your WebApi Project

    // Web Api Method 
    [Route("api/loginuser")]
    [HttpPost]
    public BaseResponse Login([FromBody]UserModel model)
    {
        // Ignorar erros de SSL
        IgnoreSSLCertificateErros();
    
        try
        {
            var response = new BaseResponse();
    
    
            if(model.Login == "Login" && model.Password == "pass")
            {
                response.Model = model;
                return response;
            }
            else
            {
                return new BaseResponse(false, "Invalid user");
            }
        }
        catch (Exception ex)
        {
            var erro = ex.Message;
            return new BaseResponse(false, "error handle");
        }
    }
    
  • Jonathan0931Jonathan0931 Member ✭✭

    yes but the ws is not mine so is not posible to change to a rest service

  • WashingtonMoraisWashingtonMorais USMember ✭✭

    You don't need to change the ws to a Web API. Make your own Web Api.
    Then call your Api through your mobile app and your Api will be responsible to make the call to the wsdl.
    this approach will help you with you need to make some validation in the data before send it to ws or same like this

  • Jonathan0931Jonathan0931 Member ✭✭

    Hi, i do what you say but when i want to obtain the value with sm.Result; my code dont respons and nothing happen

Sign In or Register to comment.