6

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?

Jamie
  • 683
  • 2
  • 11
  • 16
  • 1
    Hi, try [this](http://stackoverflow.com/questions/576513/android-download-binary-file-problems). – Pasha Feb 17 '11 at 10:04

3 Answers3

5

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));
Gero
  • 1,842
  • 25
  • 45
1

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.

StaxMan
  • 113,358
  • 34
  • 211
  • 239
0

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.

JanithaR
  • 1,094
  • 2
  • 11
  • 23