Skip to content

Instantly share code, notes, and snippets.

@luizbraga
Created November 27, 2015 15:42
Show Gist options
  • Save luizbraga/8e71de2cb88836aea711 to your computer and use it in GitHub Desktop.
Save luizbraga/8e71de2cb88836aea711 to your computer and use it in GitHub Desktop.
public String httpPost(String urlStr) throws IOException{
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (conn.getResponseCode() != 200){
throw new IOException(conn.getContentEncoding());
}
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null){
sb.append(line);
}
rd.close();
conn.disconnect();
return sb.toString();
}
public String getEndereco(String cep) {
Endereco endereco = new Endereco();
try {
String result = httpGet("http://correiosapi.apphb.com/cep/"+cep);
JSONObject obj = new JSONObject(result);
endereco = new Endereco(
Integer.parseInt(obj.getString("cep")),
obj.getString("tipoDeLogradouro"),
obj.getString("logradouro"),
obj.getString("bairro"),
obj.getString("cidade"),
obj.getString("estado"));
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return endereco.getCidade();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment