public EnderecoViaCep BuscarEnderecoPorCep(string cep) { EnderecoViaCep enderecoViaCep = new EnderecoViaCep(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://viacep.com.br/ws/" + cep + "/json/"); request.AllowAutoRedirect = false; HttpWebResponse ChecaServidor = (HttpWebResponse)request.GetResponse(); if (ChecaServidor.StatusCode != HttpStatusCode.OK) { return(enderecoViaCep); } enderecoViaCep.Cep = cep; using (Stream webStream = ChecaServidor.GetResponseStream()) { if (webStream != null) { using (StreamReader responseReader = new StreamReader(webStream)) { string response = responseReader.ReadToEnd(); response = Regex.Replace(response, "[{},]", string.Empty); response = response.Replace("\"", ""); String[] substrings = response.Split('\n'); int cont = 0; foreach (var substring in substrings) { string[] valor = substring.Split(":".ToCharArray()); if (cont == 2) { enderecoViaCep.Rua = valor[1]; } if (cont == 4) { enderecoViaCep.Bairro = valor[1]; } if (cont == 5) { enderecoViaCep.Cidade = valor[1]; } if (cont == 6) { enderecoViaCep.Uf = valor[1]; } cont++; } } } } return(enderecoViaCep); }
public async static Task <Endereco> GetEndereco(string CEP) { var HttpClient = new HttpClient(); HttpResponseMessage Resposta = await HttpClient.GetAsync($"https://viacep.com.br/ws/{CEP}/json/"); Resposta.EnsureSuccessStatusCode(); EnderecoViaCep Endereco = await Resposta.Content.ReadAsAsync <EnderecoViaCep>(); return(Endereco.ToEndereco()); }
public static Endereco ToEndereco(this EnderecoViaCep endereco) { return(new Endereco { Bairro = endereco.bairro, CEP = endereco.cep, Cidade = endereco.localidade, Complemento = endereco.complemento, Estado = endereco.uf, Rua = endereco.logradouro }); }