Android-universal-image-loader: [1.8.0] memoryCacheExtraOptions agrega los valores al Uri (https)

Creado en 1 mar. 2013  ·  25Comentarios  ·  Fuente: nostra13/Android-Universal-Image-Loader

Estoy usando .memoryCacheExtraOptions (512, 512)
No estoy seguro de si este es el efecto deseado, pero al hacer esto al realizar webrequests, ahora coloca el tamaño al final de la imagen.

https://d3jpl91pxevbkh.cloudfront.net/notha/image/upload/v1360769665/1.png
se convierte en
https://d3jpl91pxevbkh.cloudfront.net/notha/image/upload/v1360769665/1.png_512x512
Que por supuesto no se carga.

Salud,
Chris

Problem

Comentario más útil

http://stackoverflow.com/questions/14789716/android-universal-image-loader-change-hxw-url-parameters

Tal vez tengas el problema con https, prueba esta clase:

public class AuthImageDownloader extends BaseImageDownloader {
    public static final String TAG = AuthImageDownloader.class.getName();


    public AuthImageDownloader(Context context, int connectTimeout, int readTimeout) {
        super(context, connectTimeout, readTimeout);
    }

    <strong i="8">@Override</strong>
    protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {

        URL url = null;
        try {
            url = new URL(imageUri);
        } catch (MalformedURLException e) {
            Log.e(TAG, e.getMessage(), e);
        }
        HttpURLConnection http = null;

        if (Scheme.ofUri(imageUri) == Scheme.HTTPS) {
            trustAllHosts();
            HttpsURLConnection https = (HttpsURLConnection) url
                    .openConnection();
            https.setHostnameVerifier(DO_NOT_VERIFY);
            http = https;
            http.connect();
        } else {
            http = (HttpURLConnection) url.openConnection();
        }

        http.setConnectTimeout(connectTimeout);
        http.setReadTimeout(readTimeout);
        return new FlushedInputStream(new BufferedInputStream(
                http.getInputStream()));
    }

    // always verify the host - dont check for certificate
    final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        <strong i="9">@Override</strong>
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    /**
     * Trust every server - dont check for any certificate
     */
    private static void trustAllHosts() {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            <strong i="10">@Override</strong>
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] x509Certificates,
                    String s) throws java.security.cert.CertificateException {
            }

            <strong i="11">@Override</strong>
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] x509Certificates,
                    String s) throws java.security.cert.CertificateException {
            }

            <strong i="12">@Override</strong>
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[] {};
            }
        } };

        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection
                    .setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Todos 25 comentarios

http://stackoverflow.com/questions/14789716/android-universal-image-loader-change-hxw-url-parameters

Tal vez tengas el problema con https, prueba esta clase:

public class AuthImageDownloader extends BaseImageDownloader {
    public static final String TAG = AuthImageDownloader.class.getName();


    public AuthImageDownloader(Context context, int connectTimeout, int readTimeout) {
        super(context, connectTimeout, readTimeout);
    }

    <strong i="8">@Override</strong>
    protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {

        URL url = null;
        try {
            url = new URL(imageUri);
        } catch (MalformedURLException e) {
            Log.e(TAG, e.getMessage(), e);
        }
        HttpURLConnection http = null;

        if (Scheme.ofUri(imageUri) == Scheme.HTTPS) {
            trustAllHosts();
            HttpsURLConnection https = (HttpsURLConnection) url
                    .openConnection();
            https.setHostnameVerifier(DO_NOT_VERIFY);
            http = https;
            http.connect();
        } else {
            http = (HttpURLConnection) url.openConnection();
        }

        http.setConnectTimeout(connectTimeout);
        http.setReadTimeout(readTimeout);
        return new FlushedInputStream(new BufferedInputStream(
                http.getInputStream()));
    }

    // always verify the host - dont check for certificate
    final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        <strong i="9">@Override</strong>
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    /**
     * Trust every server - dont check for any certificate
     */
    private static void trustAllHosts() {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            <strong i="10">@Override</strong>
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] x509Certificates,
                    String s) throws java.security.cert.CertificateException {
            }

            <strong i="11">@Override</strong>
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] x509Certificates,
                    String s) throws java.security.cert.CertificateException {
            }

            <strong i="12">@Override</strong>
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[] {};
            }
        } };

        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection
                    .setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Nada que ver con SSL, esta línea en realidad devuelve una URL adjunta que es la razón por la que falla el cargador de imágenes.
(https://d3jpl91pxevbkh.cloudfront.net/notha/image/upload/v1360769665/1.png_512x512 que por supuesto es malo).

    <strong i="7">@Override</strong>
    protected InputStream getStreamFromNetwork(URI imageUri, Object extra) throws IOException {
      Log.d(TAG, "URL="+imageUri.toString());
      //...
    }

Buscaré arreglarlo en mi tenedor. Parece que un cierto flujo lo hace prefijar las partes incorrectas de la solicitud.

¿Encontraste la razón?

No he tenido la oportunidad de investigar este fin de semana.
El 8 de marzo de 2013 a las 09:35, "Sergey Tarasevich" [email protected] escribió:

¿Encontraste la razón?

-
Responda a este correo electrónico directamente o véalo en Gi
.

Hola @ nostra13 y @chrisjenx , tengo un problema similar, Universal Image Downloader y SSL.

Quiero usar la clase que publicaste antes, pero en el punto de anular getStreamFromNetwork:

AuthImageDownloader de clase pública extiende BaseImageDownloader {
...
@Anular
protegido InputStream getStreamFromNetwork (URI imageUri, Object extra) lanza IOException {
...
}

Ocurre este error y no estoy seguro de cómo solucionarlo:

El método getStreamFromNetwork (URI, Object) de tipo AuthImageDownloader debe anular o implementar un método de supertipo

La solución rápida es eliminar la anotación "@Override". Pero, por supuesto, no funciona.

Gracias.

Simplemente verifique que se anule el método correcto.

Si eclipse arroja un error en la anotación de anulación, significa que no está anulando / extendiendo la clase correcta, por lo que aparece el error.

ImageDownloader cambió su API, usa String en lugar de URI. Actualicé mi comentario.

Genial, ahora funciona perfecto.

Gracias, es increíble como ambos responden tan rápido. ^^

Este es mi trabajo en torno al error anterior:

package com.bizzby.http.requests;

import android.content.Context;
import android.text.TextUtils;
import com.bizzby.utils.QLog;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.http.*;
import com.nostra13.universalimageloader.core.assist.FlushedInputStream;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created with Intellij with Android, BIZZBY product.
 * See licencing for usage of this code.
 * <p/>
 * User: chris
 * Date: 01/03/2013
 * Time: 15:45
 */
public class GoogleImageDownloader extends BaseImageDownloader
{

    protected static final Pattern SIZE_PATTERN = Pattern.compile("(_[0-9]+(_|x)[0-9]+)$", Pattern.CASE_INSENSITIVE);
    public static HttpTransport sHttpTransport;
    public static HttpRequestFactory sHttpRequestFactory;

    public static HttpRequest getHttpRequest(final String uri) throws IOException
    {
        if (sHttpTransport == null) sHttpTransport = AndroidHttp.newCompatibleTransport();
        if (sHttpRequestFactory == null) sHttpRequestFactory = sHttpTransport.createRequestFactory();
        return sHttpRequestFactory.buildGetRequest(new GenericUrl(uri));
    }

    private static String replaceLast(final String string, final String from, final String to)
    {
        int lastIndex = string.lastIndexOf(from);
        if (lastIndex < 0) return string;
        final String tail = string.substring(lastIndex).replaceFirst(from, to);
        return string.substring(0, lastIndex) + tail;
    }

    static String stripSizeOffUrl(final String string)
    {
        if (TextUtils.isEmpty(string)) return string;
        final Matcher matcher = SIZE_PATTERN.matcher(string);
        String group = "";
        while (matcher.find())
        {
            group = matcher.group(1);
        }
        return replaceLast(string, group, "");

    }

    public GoogleImageDownloader(final Context context)
    {
        super(context);
    }

    public GoogleImageDownloader(final Context context, final int connectTimeout, final int readTimeout)
    {
        super(context, connectTimeout, readTimeout);
    }

    <strong i="6">@Override</strong>
    protected InputStream getStreamFromContent(URI imageUri, final Object extra) throws FileNotFoundException
    {
        imageUri = URI.create(stripSizeOffUrl(imageUri.toString()));
        return super.getStreamFromContent(imageUri, extra);
    }

    <strong i="7">@Override</strong>
    protected InputStream getStreamFromNetwork(final URI imageUri, final Object extra) throws IOException
    {
        if (null == imageUri) return null;
        final String url = stripSizeOffUrl(imageUri.toString());
        QLog.i("ImageLoader, Downloading [" + url + "]");
        final HttpRequest request = getHttpRequest(url);
        request.setConnectTimeout(connectTimeout);
        request.setReadTimeout(readTimeout);
        final HttpResponse response = request.execute();
        if (response != null && response.isSuccessStatusCode())
        {
            return new FlushedInputStream(response.getContent(), BUFFER_SIZE);
        }
        return null;
    }
}

La causa de esto todavía está en mi lista de tareas pendientes.

Yo también tengo este problema, esto no es divertido, y ¿por qué este hilo está marcado como cerrado?

@doridori no está marcado como cerrado, el otro # 163 está cerrado que hace referencia a esto.

oh lo siento, mi mal

La corrección de errores de

ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
                .imageDownloader(new CustomImageDownloader(context)) //bug fix

Todavía no puedo entender cómo pudo suceder.

Nostra, tengo problemas con https y su solución publicada anteriormente (usando la clase AuthImageDownloader).
El problema está en el método encodeCredentials (), donde dice que el método para Configuration.getInstance () no está definido.

public static String encodeCredentials() {
       try {
           Configuration configuration = Configuration.getInstance();
           String auth = android.util.Base64.encodeToString((configuration.getHttpAuthLogin()
                + ":" + configuration.getHttpAuthPassword()).getBytes("UTF-8"),
                android.util.Base64.NO_WRAP);
           return auth;
       } catch (Exception ignored) {
           Log.e(TAG, ignored.getMessage(), ignored);
       }
       return "";
   }

Me estoy perdiendo algo? ¿Cuáles son las importaciones necesarias para el código anterior?
Si importo android.content.res.Configuration, ¿obtengo aún más errores?

Debe utilizar esta autorización solo si la necesita. Supongo que no. Actualicé el código AuthImageDownloader , échale un vistazo.

¡Obras! Usé el siguiente código para que funcione:

   ImageLoaderimageLoader = ImageLoader.getInstance();

    DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
            .cacheInMemory()
            .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2).build();

    Builder configBuilder = new ImageLoaderConfiguration.Builder(getActivity());
    configBuilder.imageDownloader(new AuthImageDownloader(getActivity(), 1000, 1000));
    configBuilder.defaultDisplayImageOptions(defaultOptions);
    ImageLoaderConfiguration config=configBuilder.build();

    imageLoader.init(config);

Muchas gracias por tu rápida respuesta.

Veo que esto está cerrado, ¿ahora no agrega las dimensiones al final de la URL?

No agregaba las dimensiones antes. No pude reproducir el error y no pude imaginar por qué puede suceder. Chrisjenx prometió investigarlo, pero supongo que no lo hizo. Si tiene este error, puede enviarme su proyecto con este error para que lo investigue.

Este error aún está muy activo. Estoy fuera del condado, así que no hay posibilidad de arreglarlo.
Dori, ¿puedes confirmar en 1.8.2 ver si todavía hay un problema?

Chris.
El 10 de abril de 2013 a las 16:24, "Sergey Tarasevich" [email protected] escribió:

No agregaba las dimensiones antes. No pude reproducir el error y
No podía imaginar por qué puede suceder. Chrisjenx prometió investigarlo pero
no lo hizo, supongo. Si tiene este error, puede enviarme su proyecto.
con este error, así que lo investigaré.

-
Responda a este correo electrónico directamente o véalo en Gi
.

Tengo este problema con 1.9.3 y https en el enlace. Utilice AuthImageDownloader de su comentario.

Como se sugirió, intenté usar AuthImageDownloader para ignorar el error del certificado SSL. Pero de log cat, parece que no se está llamando al método de anulación de AuthImageDownloader y sigo recibiendo el mismo error ssl.
Ya configuré ".imageDownloader (nuevo AuthImageDownloader (getApplicationContext (), 5000,5000))" en ImageLoaderConfiguration.
¡Ayuda por favor!

Tengo este problema con 1.9.4 .... ¿Cómo solucionarlo?

¿Alguien ha encontrado una solución? Lo necesito lo antes posible.

@ nostra13 Tu código funciona bien, gracias
ps: la versión de UIL que uso es 1.9.5

¿Fue útil esta página
0 / 5 - 0 calificaciones