Skip to content

Instantly share code, notes, and snippets.

@Shujito
Last active August 29, 2015 13:57
Show Gist options
  • Save Shujito/9651937 to your computer and use it in GitHub Desktop.
Save Shujito/9651937 to your computer and use it in GitHub Desktop.
ejemplo HttpURLConnection, le faltan try catches
// nueva conexion
URL url = new URL("http://danbooru.donmai.us/posts.json?tags=setz");
// abrir
HttpURLConnection https = (HttpURLConnection) url.openConnection();
// conectar
https.connect();
// 200,401,404,500
int code = https.getResponseCode();
// OK, Access denied, Not found, Internal server error
String message = https.getResponseMessage();
// abrir el inputstream en un buffer
BufferedReader br = new BufferedReader(new InputStreamReader(https.getInputStream()));
// leer linea por linea
String l = null;
StringBuilder sb = new StringBuilder();
while ((l = br.readLine()) != null)
sb.append(l);
// convertir stringbuilder a stirng
String jsonString = sb.toString();
// parsear el string como jsonarr o jsonobject, dependiendo
JSONArray jarr = new JSONArray(jsonString);
// etc
JSONObject jobj = jarr.getJSONObject(0);
int id = jobj.getInt("id");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment