Android - download JSON file from url

前端 未结 4 1141
执念已碎
执念已碎 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: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 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.

提交回复
热议问题