-1
要求是驗證郵政編碼是否真的存在或不在特定的國家?如何使用geonames api驗證針對某個國家/地區的郵政編碼/郵政編碼?
國家= US 狀態=加州
我想知道如何使用REST通過郵政編碼來獲得國家代碼調用API GEONAMES?我比較喜歡JSON格式的輸出。
答:
參考 http://www.mkyong.com/webservices/jax-rs/restfull-java-client-with-java-net-url/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class NetClientGet {
// http://localhost:8080/RESTfulExample/json/product/get
public static void main(String[] args) {
try {
URL url = new URL("http://api.geonames.org/postalCodeSearchJSON?postalcode=94536&maxRows=1&username=demo&country=US");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
感謝Mkyong!