Jamie
Jamie

Reputation: 683

Android - download JSON file from url

Is it possible to download a file with JSON data inside it from a URL? Also, the files I need to get have no file extension, is this a problem or can i force it to have a .txt extension upon download?

UPDATE: I forgot to mention, that the website requires a username and password entered in order to access the site which i know. There a way to input these values in as I retrieve the file?

Upvotes: 6

Views: 28542

Answers (3)

JanithaR
JanithaR

Reputation: 1132

Here is a class file and an interface I have written to download JSON data from a URL. As for the username password authentication, that will depend on how it's implemented on the website you're accessing.

Upvotes: 0

StaxMan
StaxMan

Reputation: 116472

Sure. Like others have pointed out, basic URL is a good enough starting point.

While other code examples work, the actual accessing of JSON content can be one-liner. With Jackson JSON library, you could do:

Response resp = new ObjectMapper().readValue(new URL("http://dot.com/api/?customerId=1234").openStream(),Response.class);

if you wanted to bind JSON data into 'Response' that you have defined: to get a Map, you would instead do:

Map<String,Object> map = new ObjectMapper().readValue(new URL("http://dot.com/api/?customerId=1234").openStream(), Map.class);

as to adding user information; these are typically passed using Basic Auth, in which you pass base64 encoded user information as "Authorization" header. For that you need to open HttpURLConnection from URL, and add header; JSON access part is still the same.

Upvotes: 1

Gero
Gero

Reputation: 1841

Have you tried using URLConnection?

private InputStream getStream(String url) {
    try {
        URL url = new URL(url);
        URLConnection urlConnection = url.openConnection();
        urlConnection.setConnectTimeout(1000);
        return urlConnection.getInputStream();
    } catch (Exception ex) {
        return null;
    }
}

Also remember to encode your params like this:

String action="blabla";
InputStream myStream=getStream("http://www.myweb.com/action.php?action="+URLEncoder.encode(action));

Upvotes: 5

Related Questions