Java examples for Network:URL Download
Create Json object and post to URL
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import org.json.JSONArray; import org.json.JSONObject; public class Main { class JThread extends Thread { String result = ""; URL uri;/*from w w w . ja v a 2 s. co m*/ public JThread(String url) throws URISyntaxException, MalformedURLException { uri = new URL(url); } @Override public void run() { try { HttpURLConnection con = (HttpURLConnection) uri .openConnection(); con.setRequestMethod("GET"); con.connect(); int status = con.getResponseCode(); if (status == HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader( new InputStreamReader(con.getInputStream(), "iso-8859-1"), 1024); StringBuffer sb = new StringBuffer(); String line = null; while ((line = br.readLine()) != null) { sb.append(line).append('\n'); } br.close(); result = sb.toString(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } ArrayList<HashMap<String, String>> list = new ArrayList<>(); JSONObject json = new JSONObject(result); JSONArray earthquakes = json.getJSONArray("earthquakes"); for (Object object : earthquakes) { JSONObject e = (JSONObject) object; HashMap<String, String> map = new HashMap<>(e.length()); map.put("datetime", e.getString("datetime")); map.put("depth", e.getDouble("depth") + ""); map.put("lng", e.getDouble("lng") + ""); map.put("src", e.getString("src")); map.put("eqid", e.getString("eqid")); map.put("magnitude", e.getDouble("magnitude") + ""); map.put("lat", e.getDouble("lat") + ""); list.add(map); } System.out.println(list); } } public static void main(String[] args) { new Main().run(); } private void run() { String url = "http://api.geonames.org/earthquakesJSON?formatted=true&north=43&south=33&east=131&west=124&username=mailofnsh"; try { new JThread(url).start(); } catch (URISyntaxException e) { e.printStackTrace(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }