我試圖從java程序中的web服務獲得結果。我已經完成了xml服務,但是這是基於文本的,我無法弄清楚如何記錄響應。如何解析txt網絡服務
這裏是web服務:http://ws.geonames.org/countryCode?lat=47.03&lng=10.2
謝謝!
我試圖從java程序中的web服務獲得結果。我已經完成了xml服務,但是這是基於文本的,我無法弄清楚如何記錄響應。如何解析txt網絡服務
這裏是web服務:http://ws.geonames.org/countryCode?lat=47.03&lng=10.2
謝謝!
如果只有文本,您不使用任何標準格式(如SOAP),你需要使用套接字:
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>();
使用這個,如果你有許多行:
while ((inputLine = in.readLine()) != null)
response.add(inputLine);
或者用這個,如果你有(你的問題,如Web服務),只有一條線:
String countryCode = in.readLine();
和塗料:
serviceConnection.close();
在我的情況下,COUNTRYCODE這是 「AT」
真棒。謝謝! – nwnoga 2012-07-10 20:31:15
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");
}
}
除了URL的另一種實現方法是使用一個HttpClient的。
您對REST服務使用什麼實現?澤西? – smcg 2012-07-10 19:03:57
典型的結果是什麼,你想得到什麼? – fdomig 2012-07-10 19:04:42
它將返回一個兩個字母的國家代碼,這就是我需要的。 – nwnoga 2012-07-10 19:07:56