Android - download json file from url

Is it possible to load a file with JSON data inside it from a URL? Also, the files that I need to receive do not have a file extension, is this a problem, or can I get it to have a .txt extension after downloading?

UPDATE: I forgot to mention that the website requires a username and password to access the site that I know. Is there a way to enter these values โ€‹โ€‹when receiving a file?

+4
source share
4 answers

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 parameters as follows:

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

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(); 
+1
source

Sure. As others have pointed out, the main URL is a pretty good starting point.

While other code examples work, actual access to JSON content can be single-line. Using the Jackson JSON library, you can do:

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

if you want to link the JSON data in the โ€œAnswerโ€ that you defined: to get the map, you must:

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

regarding adding user information; they are usually transmitted using Basic Auth , in which you pass the base64 encoded user information as the "Authorization" header. To do this, you need to open the HttpURLConnection from the URL and add a header; The JSON access part remains the same.

+1
source

Here is the class file and the interface that I wrote to load JSON data from the URL. Regarding the authentication of the username password, this will depend on how it is implemented on the website you are accessing.

0
source

Source: https://habr.com/ru/post/1340150/


All Articles