Get external json on android with java

0

I need to access an external configuration file that is in json format.

I have this code but it does not work for me:

String stringUrl = "url_to_json/configuracion.json";
String respuesta = "";
StringBuilder response = null;
try {
    URL url = new URL(stringUrl);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("charset", "utf-8");
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    response = new StringBuilder();
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    respuesta = response.toString();
} catch (Exception  e) {
    respuesta = "Error->" + e.getMessage();
}
Log.d(TAG, "Configuración Menu->" + respuesta);

The answer I get from the console is this:

Configuración Menu->Error->null
    
asked by Elenasys 02.09.2016 в 11:21
source

1 answer

0

Your Url defined is incorrect, does not exist or does not have the protocol "http: //" for this reason you would not get the desired .json, ensure it is a valid url.

String stringUrl = "url_to_json/configuracion.json";

You can add this block in your exception handling to trap the error MalformedURlException and IOException , to have more detail:

...
...
     } catch (MalformedURLException e) {
            respuesta += "MalformedURLException ->" + e.getMessage();
      }catch(IOException e) {
            respuesta += "IOException ->" + e.getMessage();
      }

    Log.d(TAG, "Configuración Menu->" + respuesta);
    
answered by 02.09.2016 / 16:19
source