download from URL and set connection property - Java Network

Java examples for Network:URL Download

Description

download from URL and set connection property

Demo Code


//package com.java2s;

import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Main {
    public static void main(String[] argv) throws Exception {
        String URL = "java2s.com";
        long nPos = 2;
        String savePathAndFile = "java2s.com";
        down(URL, nPos, savePathAndFile);
    }/*from w  ww. java 2 s  .co m*/

    public static void down(String URL, long nPos, String savePathAndFile) {
        try {
            URL url = new URL(URL);
            HttpURLConnection httpConnection = (HttpURLConnection) url
                    .openConnection();
            // User-Agent
            httpConnection.setRequestProperty("User-Agent", "NetFox");
            // 
            httpConnection.setRequestProperty("RANGE", "bytes=" + nPos);
            // 
            InputStream input = httpConnection.getInputStream();
            RandomAccessFile oSavedFile = new RandomAccessFile(
                    savePathAndFile, "rw");
            // nPos?
            oSavedFile.seek(nPos);
            byte[] b = new byte[1024];
            int nRead;

            while ((nRead = input.read(b, 0, 1024)) > 0) {
                (oSavedFile).write(b, 0, nRead);
            }
            httpConnection.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Related Tutorials