HttpURLConnection下载数据太慢了

时间:2016-12-20 11:26:28

标签: android http download httpurlconnection

我已经制作了一个应用程序,它将从youtube视频下载数据并处理它以获取视频图像和标题和视频质量,但它花费了太多时间,应用程序是Buggy有我的代码:

package amaigh.halzoun;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class MainActivity extends Activity {
    int contentlenght;
    public class DownloadTask extends AsyncTask<String, Void , String> {
        @Override
        protected String doInBackground(String... urls) {
            String result = "";
            URL url;
            HttpURLConnection urlConnection = null;

            try {

                url = new URL(urls[0]);

                urlConnection = (HttpURLConnection)url.openConnection();
                contentlenght = urlConnection.getResponseCode();
                if (contentlenght == 200) {
                    InputStream in = urlConnection.getInputStream();
                    InputStreamReader reader = new InputStreamReader(in);

                    int data = reader.read();

                    while (data != -1) {

                        char current = (char) data;

                        result += current;

                        data = reader.read();

                    }

                    return result;
                }
                else
                    return "Connection Lost";

            }
            catch(Exception e) {

                e.printStackTrace();

                return "Failed";

            }


        }

    }
    public class ImageDownload extends AsyncTask<String,Void,Bitmap>{

        @Override
        protected Bitmap doInBackground(String... urls) {
            try{
                URL url = new URL(urls[0]);
                Log.i("DOWNLOAD IMAGE URL:" ,url.toString());
                HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
                urlConnection.connect();
                InputStream in = urlConnection.getInputStream();
                Bitmap image = BitmapFactory.decodeStream(in);
                return image;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
    public void Start (View view)
    {
        String Url = "";
        ImageView VideoImage = (ImageView)findViewById(R.id.imageView2);
        EditText URLInput = (EditText)findViewById(R.id.URL);
        Url = URLInput.getText().toString();
        Log.i("Original URL: ", Url);
        Url = Url.replace("watch?v=","embed/");
        Log.i("Title URL: ", Url);
        DownloadTask GetTitle = new DownloadTask();
        String result = "";
        String VideoUrl = Url.replace("https://www.youtube.com/embed/","https://i.ytimg.com/vi/");
        VideoUrl += "/hqdefault.jpg";
        ImageDownload imageDownloader = new ImageDownload();
        Bitmap image = null;
        try {

            result = GetTitle.execute(Url).get();
            image = imageDownloader.execute(VideoUrl).get();
            VideoImage.setImageBitmap(image);

        } catch (InterruptedException e) {

            e.printStackTrace();

        } catch (ExecutionException e) {

            e.printStackTrace();

        }
        GetTitle(result);
        Url = URLInput.getText().toString();
        DownloadTask GetVideoInfo = new DownloadTask();
        result = "";

        try {

            result = GetVideoInfo.execute(Url).get();

        } catch (InterruptedException e) {

            e.printStackTrace();

        } catch (ExecutionException e) {

            e.printStackTrace();

        }
        Log.i("Resultat: ", result);

    }
    public void GetTitle(String Content){
        String searchString = "<title>(.*?)</title>";
        Pattern p = Pattern.compile(searchString);
        TextView VideoTitle = (TextView)findViewById(R.id.VideoTitle);
        Matcher m = p.matcher(Content);
        while (m.find()){
            Log.i("Title: ", m.group(1));
            VideoTitle.setText(m.group(1));
        }
    }
    public void GetInfo(String Content){
        ArrayList<String> VideoQuality = new ArrayList<>();
        String searchString = "quality_label=(.*?)p";
        Pattern p = Pattern.compile(searchString);
        Matcher m = p.matcher(Content);
        while (m.find()){
            VideoQuality.add(m.group(0).replace("quality_label=",""));
        }
        int a = 0;

        VideoQuality.remove(0);
        VideoQuality.remove(2);
        VideoQuality.remove(4);
        VideoQuality.remove(6);
        VideoQuality.remove(8);
        VideoQuality.remove(10);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,VideoQuality);
        Spinner Spinner = (Spinner)findViewById(R.id.spinner);
        Spinner.setAdapter(adapter);
    }

}

请告诉我我做错了什么

1 个答案:

答案 0 :(得分:0)

您可以使用Spring的Restful Web Services,它可以通过减少处理时间和提高效率来帮助您。 你可以通过对象或其他方法从webUrl下载数据, 它还减少了解析数据的麻烦,也减少了代码的大小。

如需参考,请访问:https://spring.io/guides/gs/consuming-rest/