java download speed very slow with this code

463 views Asked by At
//    Uploaded.net API - Java
//    Copyright (C) 2012  Julius Fischer [email protected]
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.

package to.uploaded.file;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import to.uploaded.Uploaded;
import to.uploaded.exception.DownloadFailedException;

public class UPDownload extends UPDownloadEventListener{

    private Uploaded uploaded;
    private String path = "";
    private String fileId = "";
    private File endFile = null;
    private long progressByte = 0;
    private long contentLength = -1;

    public UPDownload(Uploaded uploaded, String path, String fileId)
    {
        this.uploaded = uploaded;
        this.fileId = fileId;

        if(!path.matches("/$"))
            path = path + "/";

        this.path = path;
    }

    /**
     * Gibt File Objekt der heruntergeladenen Datei zurück
     * @return
     */
    public File getFile()
    {
        return endFile;
    }

    private String getDownloadLink(String fileId) throws DownloadFailedException
    {
        try {

            DefaultHttpClient httpclient    = uploaded.getUpHttp().getUpClient();
            HttpClientParams.setRedirecting(httpclient.getParams(), false);

            HttpResponse response = httpclient.execute(new HttpGet("http://uploaded.net/file/" + fileId +"/ddl"));

            Header location = response.getLastHeader("Location");
            String content  = null;

            if(location != null)
            {
                content = location.getValue();

                if(content != null)
                {
                    Matcher mat = Pattern.compile("http://[0-9a-z\\-]*stor\\d+.uploaded.net/dl/([0-9a-z-]+)").matcher(content);

                    if(mat.find())
                    {
                        httpclient.getConnectionManager().shutdown();

                        return mat.group(0);
                    }
                }
            }

            content =  EntityUtils.toString(response.getEntity());

            if(content.matches("<title>(.*?)Wartungsarbeiten</title>")) {
                throw new DownloadFailedException("Wartungsarbeiten");
            }

            if(content != null)
            {
                Matcher mat = Pattern.compile("http://[0-9a-z\\-]*stor\\d+.uploaded.net/dl/([0-9a-z-]+)").matcher(content);

                if(mat.find())
                {
                    httpclient.getConnectionManager().shutdown();

                    return mat.group(0);
                }
            }

            httpclient.getConnectionManager().shutdown();

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * Startet den Downloadvorgang
     * @throws DownloadFailedException 
     */
    public void start() throws DownloadFailedException
    {       
        if(!isFileAvailable())
            throw new DownloadFailedException("Datei nicht mehr auf Uploaded.net vorhanden");

        endFile = null;

        DefaultHttpClient httpclient    = uploaded.getUpHttp().getUpClient();

        try {

            HttpResponse response;
            String url = getDownloadLink(fileId);

            if(url == null)
                throw new DownloadFailedException("Downloadserver konnte nicht gefunden werden");

            response = httpclient.execute(new HttpGet(url));
            HttpEntity entity = response.getEntity();

            String filename = response.getHeaders("Content-Disposition")[0].getValue();

            Matcher mat = Pattern.compile("attachment; filename=\"([^\\\\/\\:\\*\\?\\\"\\<\\>\\|]+)\"").matcher(filename);

            if(!mat.find())
                throw new DownloadFailedException("Dateiname nicht gefunden");

            filename = mat.group(1);

            File file = new File(path + filename);

            if(file.exists())
                throw new DownloadFailedException("Dateiname existiert bereits");

            file.createNewFile();

            OutputStream out = new BufferedOutputStream(new FileOutputStream(file.getAbsoluteFile()));

            InputStream in = entity.getContent();

            contentLength = entity.getContentLength();

            byte[] b = new byte[1024];
            int numRead;

            while ((numRead = in.read(b)) != -1) {
                out.write(b, 0, numRead);
                updateProgress(numRead);
            }

            in.close();
            out.close();
            httpclient.getConnectionManager().shutdown();

            endFile = file;


        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * Überprüft eine Datei auf Verfügbarkeit
     * 
     * @return true = OK | false = 404
     */
    public boolean isFileAvailable() 
    {
        try {

            DefaultHttpClient httpclient    = uploaded.getUpHttp().getUpClient();

            HttpResponse response = httpclient.execute(new HttpGet("http://uploaded.net/file/" + this.fileId +"/ddl"));

            httpclient.getConnectionManager().shutdown();

            if(response.getStatusLine().getStatusCode() == 404)
                return false;

            return true;

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return false;
    }

    public boolean isFinish()
    {
        return contentLength == progressByte;
    }

    /**
     * @return the progressByte
     */
    public long getProgressByte() {
        return progressByte;
    }

    /**
     * @return the contentLength
     */
    public long getContentLength() {
        return contentLength;
    }

    private void updateProgress(long i)
    {
        progressByte += i;
        notifyListeners(this);
    }

    public static interface UPDownloadProgress
    {
        void progress(UPDownload upDownload);
    }
}

ok so i have an uploaded.net download api ... the problem is that code is kinda slow , when i download the file via chorme i get up to 70mb/s speed with this api ~ 4-5mb/s with is very slow ...

I dont know why the difference is so big.. does anyone know how to fix this?

THank you

0

There are 0 answers