Timeout error when loading data url android

3

I am developing an application in Android Studio (api min is 10). In this application I charge the data I get through a url. When the device in which I test it is larger than api 10, it performs correctly. However, when it is api 10, nothing is received. How can I solve this?

The code of the task in background is the following:

private class DownloadJsonTask extends AsyncTask<String, Void, ArrayList<String>> {

    private ArrayList<String> parseJsonCentrosFile(String jsonLibrosInformation)
            throws JSONException {

           //Parseo de los datos
    }

    @Override
    protected ArrayList<String> doInBackground(String... urls) {

        try {
            return downloadUrl(urls[0]);
        } catch (IOException e) {

            return null;
        }
    }
    private ArrayList<String> downloadUrl(String myUrl) throws IOException {
        InputStream is = null;
        try {
            is = openHttpInputStream(myUrl);

            try {
                return parseJsonCentrosFile(streamToString(is));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } finally {

            if (is != null) {
                is.close();
            }
        }
        return null;
    }


    public String streamToString(InputStream stream) throws IOException,
            UnsupportedEncodingException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];
        int length = 0;
        do {
            length = stream.read(buffer);
            if (length != -1) {
                baos.write(buffer, 0, length);
            }
        } while (length != -1);
        return baos.toString("UTF-8");
    }

    @Override
    protected void onPostExecute(ArrayList<String> result) {

      //Código de onPostExecute

    }
} 

Get connection code:

 private InputStream openHttpInputStream(String myUrl)
        throws MalformedURLException, IOException, ProtocolException {
    InputStream is;
    URL url = new URL(myUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");

    conn.connect();
    is = conn.getInputStream();
    return is;
} 

The file that is accessed by the url does not download it, so I think the error is that. How could I download the json and then read it from the file that I downloaded?

The logCat error is as follows:

04-14 18:36:53.281 793-807/
es.libros/AndroidRuntime:FATAL EXCEPTION: AsyncTask #1
                                                                                 java.lang.RuntimeException: An error occured while executing doInBackground()
                                                                         at android.os.AsyncTask$3.done(AsyncTask.java:278)
                                                                         at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
                                                                         at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
                                                                         at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
                                                                         at java.util.concurrent.FutureTask.run(FutureTask.java:137)
                                                                         at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
                                                                         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
                                                                         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
                                                                         at java.lang.Thread.run(Thread.java:856)
                                                                      Caused by: java.lang.OutOfMemoryError
                                                                         at java.io.ByteArrayOutputStream.expand(ByteArrayOutputStream.java:91)
                                                                         at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:201)
                                                                         at es.user.bares_restaurantes.BarListFragment$DownloadJsonTask.streamToString(BarListFragment.java:703)
                                                                         at es.user.bares_restaurantes.BarListFragment$DownloadJsonTask.downloadUrl(BarListFragment.java:677)
                                                                         at es.user.bares_restaurantes.BarListFragment$DownloadJsonTask.doInBackground(BarListFragment.java:664)
                                                                         at es.bares_restaurantes.BarListFragment$DownloadJsonTask.doInBackground(BarListFragment.java:328)
                                                                         at android.os.AsyncTask$2.call(AsyncTask.java:264)
                                                                         at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
                                                                         at java.util.concurrent.FutureTask.run(FutureTask.java:137) 
                                                                         at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208) 
                                                                         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 
                                                                         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569) 
                                                                         at java.lang.Thread.run(Thread.java:856) 
    
asked by adamista 02.04.2016 в 19:40
source

2 answers

1

Discarding the timeout in the connection we have The problem is a " Unexpected end of Stream ", probably caused by accented characters.

Change your streamToString() method using StringBuilder :

public String streamToString(InputStream stream) {
    try {
        BufferedReader r = new BufferedReader(new InputStreamReader(stream));
        StringBuilder totalDatos = new StringBuilder();
        String line;
        while ((line = r.readLine()) != null) {
            totalDatos.append(line);
        }
        return totalDatos.toString();
    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, "UnsupportedEncodingException: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "IOException : " + e.getMessage());
    }
    return null;
}

You can also modify your openHttpInputStream() method to get the InputStream if the connection was successful, code 200 and thus verify that there is no problem.

private InputStream openHttpInputStream(String myUrl) {
    InputStream is = null;
    try {

        URL url = new URL(myUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.connect();
        int connCode= conn.getResponseCode();
        if (connCode== HttpURLConnection.HTTP_OK) {
            is = conn.getInputStream();
            Log.e(TAG, "SE REALIZO LA CONEXION!, código " +  connCode);
        } else {
            Log.e(TAG, "NO SE PUDO REALIZAR LA CONEXION!");
        }
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
    } 
    return is;
}

Once these changes are made, you can run your Asynctask and get the data without problems:

String url = "https://www.turismoasturias.es/open-data/catalogo-de-datos?p_p_id=opendata_WAR_importportlet&p_p_lifecycle=2&p_p_state=normal&p_p_mode=view&p_p_resource_id=exportJson&p_p_cacheability=cacheLevelPage&p_p_col_id=column-1&p_p_col_count=1&_opendata_WAR_importportlet_structure=27548&_opendata_WAR_importportlet_robots=nofollow";
new DownloadJsonTask().execute(url); 

Another important way to optimize downloads on mobile devices is to compress the file to be downloaded, to .gzip format, for example the file you want to download, containing text, if compressed it dramatically reduces the size ! :

Then we made a change in our method for obtaining data from the URL:

private InputStream openHttpInputStream(String myUrl) {
    InputStream is = null;
    try {
        URL url = new URL(myUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept-Encoding", "gzip");
        conn.connect();
        int resCode = conn.getResponseCode();
        Log.i(TAG, "resCode : " + resCode);
        if (resCode == HttpURLConnection.HTTP_OK) {
            Log.i(TAG, "Se realizo la conexión!");
            is = conn.getInputStream();
            if(myUrl.indexOf(".gz")>0){ //detectamos si el archivo esta compreso.
                is = new GZIPInputStream(is);
                Log.i(TAG, "El url esta compreso como .gzip!");
            }
        } else {
            Log.e(TAG, "NO SE PUDO REALIZAR LA CONEXION! errorCode: " + resCode);
        }
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
    }
    return is;
}

Now if we review the time it takes to download the data instead of almost 20 seconds, now it takes less than 1 second:

    
answered by 02.04.2016 в 21:16
0

I add a new answer since I am editing the question and it does not correspond to the original problem "Timeout error when loading url android data", now the problem is:

  

ExceptionIE:
  org.bouncycastle.jce.exception.ExtCertPathValidatorException: Could   not validate certificate signature. 04-04 17: 55: 12.647   3641-3705 / en.project E / AndroidRuntime: FATAL EXCEPTION: AsyncTask

This error may be due to different causes but even if it is ridiculous, it may be because your device / emulator is configured with the wrong time and date.

I think this is the problem because first you had no problem reading the file but to process it.

    
answered by 12.04.2016 в 01:55