I’m new to Java and I’m trying to create a lib for fetching Brazilian addresses from a webservice but I can’t read the response.
in the constructor of the class I have this result string to which I want to append the response, once this variable is populated with the response I will know what to do.
The problem is: for some reason, I guess the BufferedReader object is not working so there is no response to be read :/
Here is the code:
package cepfacil;
import java.net.*;
import java.io.*;
import java.io.IOException;
public class CepFacil {
final String baseUrl = "http://www.cepfacil.com.br/service/?filiacao=%s&cep=%s&formato=%s";
private String zipCode, apiKey, state, addressType, city, neighborhood, street, status = "";
public CepFacil(String zipCode, String apiKey) throws IOException {
String line = "";
try {
URL apiUrl = new URL("http://www.cepfacil.com.br/service/?filiacao=" + apiKey + "&cep=" +
CepFacil.parseZipCode(zipCode) + "&formato=texto");
String result = "";
BufferedReader in = new BufferedReader(new InputStreamReader(apiUrl.openStream()));
while ((line = in.readLine()) != null) {
result += line;
}
in.close();
System.out.println(line);
} catch (MalformedURLException e) {
e.printStackTrace();
}
this.zipCode = zipCode;
this.apiKey = apiKey;
this.state = state;
this.addressType = addressType;
this.city = city;
this.neighborhood = neighborhood;
this.street = street;
}
}
So here is how the code is supposed to work, you build an object like this:
String zipCode = "53416-540";
String token = "0E2ACA03-FC7F-4E87-9046-A8C46637BA9D";
CepFacil address = new CepFacil(zipCode, token);
// so the apiUrl object string inside my class definition will look like this:
// http://www.cepfacil.com.br/service/?filiacao=0E2ACA03-FC7F-4E87-9046-A8C46637BA9D&cep=53416540&formato=texto
// which you can check, is a valid url with content in there
I’ve omitted some parts of this code for brevity but all the methods called in the constructor are defined in my code and there is no compilation or runtime error going on.
I’d appreciate any help you could give me and I’d love to hear the simplest posible solutions 🙂
Thanks in advance!
UPDATE: now that I could fix the problem (huge props to @Uldz for pointing me the problem out) it is open sourced http://www.rodrigoalvesvieira.com/cepfacil/
In
you output line not the result. Maybe last line is empty?