Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

java - Android - download JSON file from url

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...