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?
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));
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.
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();
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.