Android - download JSON file from url

前端 未结 4 1142
执念已碎
执念已碎 2020-12-18 04:58

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 .t

相关标签:
4条回答
  • 2020-12-18 05:11

    Basically you would do something like:

    Code:

    URL address = URL.parse("http://yoururlhere.com/yourfile.txt"); 
    URLConnection conn = new URLConnection(address);
    InputStream is = conn.getInputStream(); 
    BufferedInputStream bis = new BufferedInputStream(is);
    ByteArrayBuffer bab = new ByteArrayBuffer(64); 
    int current = 0;
    
    while((current = bis.read()) != -1) {
      bab.append((byte)current); 
    }
    
    FileOutputStream fos = new FileOutputStream(new File(filepath));
    fos.write(bab.toByteArray());
    fos.close();
    
    0 讨论(0)
  • 2020-12-18 05:17

    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));
    
    0 讨论(0)
  • 2020-12-18 05:18

    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.

    0 讨论(0)
  • 2020-12-18 05:24

    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.

    0 讨论(0)
提交回复
热议问题