public async Task <dynamic> GetEnderecoPorCEP(string cep, string token) { if (Utils.ValidateToken(token)) { ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri("https://viacep.com.br/"); var resp = await client.GetAsync("ws/" + cep + "/json"); if (resp.IsSuccessStatusCode) { string response = resp.Content.ReadAsStringAsync().Result; EnderecoCEP end = JsonConvert.DeserializeObject <EnderecoCEP>(response); return(end); } else { return(Request.CreateResponse(HttpStatusCode.BadRequest, "Favor validar o CEP")); } } } else { return(Request.CreateResponse(HttpStatusCode.Unauthorized, "Token Inválido")); } }
public static EnderecoCEP BuscaCEP(string cep) { cep = cep.Replace("-", string.Empty); // remove o hífen Match regex = Regex.Match(cep, "^[0-9]{8}$"); if (!regex.Success) { return(null); } EnderecoCEP addr = null; using (HttpClient hc = new HttpClient()) { var values = new Dictionary <string, string> { { "relaxation", cep }, { "tipoCep", "ALL" }, { "semelhante", "N" } }; var content = new FormUrlEncodedContent(values); var response = hc.PostAsync("http://www.buscacep.correios.com.br/sistemas/buscacep/resultadoBuscaCepEndereco.cfm", content).Result; var responseText = response.Content.ReadAsStringAsync().Result; MatchCollection matches = Regex.Matches(responseText, "<td.*?>(.*?)</td>"); if (matches.Count == 2) { addr = new EnderecoCEP { cep = cep, cidade = matches[0].Groups[1].Value.Replace(" ", ""), UF = matches[1].Groups[1].Value.Replace(" ", ""), }; } else if (matches.Count == 4) { string cidade_estado = matches[2].Groups[1].Value.Replace(" ", ""); string[] split = cidade_estado.Split('/'); string rua = matches[0].Groups[1].Value.Replace(" ", ""); var rua_match = Regex.Matches(rua, "<a.*?>(.*?)<br><br>.*?</a>"); if (rua_match.Count == 1) { rua = rua_match[0].Groups[1].Value; } addr = new EnderecoCEP { cep = cep, rua = rua, bairro = matches[1].Groups[1].Value.Replace(" ", ""), cidade = split[0], UF = split[1] }; } } return(addr); }
public string Enviar(EnderecoCEP objModel) { throw new NotImplementedException(); }
public static GeoCoordinate BuscaCoordEnd(EnderecoCEP end) { return(BuscaCoordEnd(end.cidade, end.rua, end.bairro, "", end.UF)); }