nwnoga
nwnoga

Reputation: 575

How to parse a txt web service

I'm trying to obtain a result from a web service in a java program. I've done xml services before but this one is text based and i can't figure out how to record the response.

Here is the webService: http://ws.geonames.org/countryCode?lat=47.03&lng=10.2

Thanks!

Upvotes: 0

Views: 182

Answers (3)

fdomig
fdomig

Reputation: 4457

public class CountryCodeReader {

    private String readAll(Reader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }

    public String readFromUrl(String url) throws IOException, JSONException {
        InputStream is = new URL(url).openStream();
        try {
            InputStreamReader is = new InputStreamReader(is, Charset.forName("UTF-8"))
            BufferedReader rd = new BufferedReader(is);

            return readAll(rd);
        } finally {
            is.close();
        }
        return null;
    }

    public static void main(String[] argv) {
        CountryCodeReader ccr = new CountryCodeReader(); 
        String cc = ccr.readFromUrl("http://ws.geonames.org/countryCode?lat=47.03&lng=10.2");
    }

}

Upvotes: 0

Zechgron
Zechgron

Reputation: 1

An alternative implementation in addition to URL is to use a HttpClient.

Upvotes: 0

Imaky
Imaky

Reputation: 1257

If it's only text, and you doesn't use any standard format (like SOAP), you need to use Sockets:

URL myURL = new URL("http://ws.geonames.org/countryCode?lat=47.03&lng=10.2");
URLConnection serviceConnection = myURL.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
                               serviceConnection.getInputStream()));

List<String> response =new ArrayList<String>();

Use this if you had many lines:

while ((inputLine = in.readLine()) != null) 
   response.add(inputLine);

Or use this if you had ONLY ONE line (like the Web Service in your question):

String countryCode = in.readLine();

And finish with:

serviceConnection.close();

In my case, countryCode it was "AT"

Upvotes: 1

Related Questions