First, to be clear API that you reported is not official Post office. This was a well-discussed subject here and here on an efficient way to obtain this data.
Now, if you really want to use the source of this site, just make a simple call with the class HttpURLConnection
(in a thread different, of course) and get the result, which is an object JSON. Something more or less like this:
private class BuscarCepTask extends AsyncTask<String, Void, String> {
URL url = null;
HttpURLConnection httpURLConnection = null;
@Override
protected String doInBackground(String... params) {
StringBuilder result = null;
int respCode = -1;
try {
url = new URL("http://cep.correiocontrol.com.br/" + params[0] + ".json");
httpURLConnection = (HttpURLConnection) url.openConnection();
do {
if (httpURLConnection != null) {
respCode = httpURLConnection.getResponseCode();
}
} while (respCode == -1);
if (respCode == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
result = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
result.append(line);
}
br.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
httpURLConnection = null;
}
}
return (result != null) ? result.toString() : null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject object = new JSONObject(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
And make the call like this:
BuscarCepTask buscarCep = new BuscarCepTask();
buscarCep.execute("02011200");
The result that is in the method onPostExecute
comes in the object that is a JSONObject
, just get object.getString("logradouro")
and any other key in the object.
After I went to find out you’re not a post office official. But as for the code, how will I take the JSON values and inform in a Textview for example?
– Felipe Miranda
It was just my final remark. Within
object
you own what you need. If you want the neighborhood,object.getString("bairro")
and so on, according to the key of the JSON. And then just define the text of yourTextView
with this information.– Paulo Rodrigues
I understood, in the case how I would take a specific cep from an Edittext and put it as a parameter instead of passing any cep?
– Felipe Miranda
Use
editText.getText().toString()
, whereeditText
is your interface object. So you pass inside the method where I am using hard code.– Paulo Rodrigues
I pass the object "street" to my Textview through the setText method ?
– Felipe Miranda
If
logradouro
is a String, yes.– Paulo Rodrigues
Let’s go continue this discussion in chat.
– Felipe Miranda