2011-08-18 22 views
11

Necesito usar cookies en una conexión https desde una aplicación nativa de Android. Estoy usando RestTemplate.Spring Android: utilizando RestTemplate con https y cookies

Comprobación de otros hilos (. Ej Setting Security cookie using RestTemplate) yo era capaz de manejar las cookies dentro de una conexión http:

restTemplate.setRequestFactory(new YourClientHttpRequestFactory()); 

donde YourClientHttpRequestFactory extends SimpleClientHttpRequestFactory

esto funciona bien en http pero no en https.

Por otro lado yo era capaz de resolver el problema https de Android confiar en el certificado SSL:

restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(HttpUtils.getNewHttpClient())); 

donde HttpUtils se describe aquí: http://www.makeurownrules.com/secure-rest-web-service-mobile-application-android.html

Mi problema es que necesito utilice una única implementación de ClientHttpRequestFactory. Así que tienen 3 opciones:

1) encontrar una manera de manejar https utilizando SimpleClientHttpRequestFactory

2) encontrar una manera de manejar las galletas usando HttpComponentsClientHttpRequestFactory

3) utilizar otro enfoque

+1

¡Gracias por el enlace HttpUtils! Estaba desesperado por una solución SSL y otras sugerencias no ayudaron. – Solata

Respuesta

8

que tenía el mismo problema. Aquí está mi solución:

Primero, manejé SSL de la misma manera que usted (utilicé el método de Bob Lee).

Las cookies son una historia diferente. La forma en que he manejado las cookies en el pasado sin RestTemplate (es decir, simplemente usando la clase HttpClient de Apache directamente) es pasar una instancia de HttpContext al método de ejecución de HttpClient. Vamos a dar un paso atrás ...

HttpClient tiene una serie de métodos sobrecargados execute, uno de los cuales es:

execute(HttpUriRequest request, HttpContext context) 

La instancia de HttpContext puede tener una referencia a un CookieStore. Cuando se crea una instancia de HttpContext, proporcionar una CookieStore (ya sea uno nuevo, o uno que ha guardado de una solicitud anterior):

private HttpContext createHttpContext() { 

    CookieStore cookieStore = (CookieStore) StaticCacheHelper.retrieveObjectFromCache(COOKIE_STORE); 
    if (cookieStore == null) { 
     Log.d(getClass().getSimpleName(), "Creating new instance of a CookieStore"); 
     // Create a local instance of cookie store 
     cookieStore = new BasicCookieStore(); 
    } 

    // Create local HTTP context 
    HttpContext localContext = new BasicHttpContext(); 
    // Bind custom cookie store to the local context 
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); 
    return localContext; 
} 

Por supuesto, usted puede agregar las galletas a la instancia de CookieStore antes de enviar la solicitud Si te gusta. Ahora cuando se llama al método de ejecución, utilice esa instancia de HttpContext:

HttpResponse response = httpClient.execute(httpRequester, localContext); 

(donde httpRequester es una instancia de HttpPost, HttpGet, etc.)

Si necesita volver a enviar las cookies en las solicitudes posteriores, asegúrese de almacenar las galletas en alguna parte:

StaticCacheHelper.storeObjectInCache(COOKIE_STORE, localContext.getAttribute(ClientContext.COOKIE_STORE), MAX_MILLISECONDS_TO_LIVE_IN_CACHE); 

La clase StaticCacheHelper que se utiliza en este código es sólo una clase personalizada que puede almacenar datos en un mapa estático:

public class StaticCacheHelper { 

private static final int TIME_TO_LIVE = 43200000; // 12 hours 

private static Map<String, Element> cacheMap = new HashMap<String, Element>(); 

/** 
* Retrieves an item from the cache. If found, the method compares 
* the object's expiration date to the current time and only returns 
* the object if the expiration date has not passed. 
* 
* @param cacheKey 
* @return 
*/ 
public static Object retrieveObjectFromCache(String cacheKey) { 
    Element e = cacheMap.get(cacheKey); 
    Object o = null; 
    if (e != null) { 
     Date now = new Date(); 
     if (e.getExpirationDate().after(now)) { 
      o = e.getObject(); 
     } else { 
      removeCacheItem(cacheKey); 
     } 
    } 
    return o; 
} 

/** 
* Stores an object in the cache, wrapped by an Element object. 
* The Element object has an expiration date, which will be set to 
* now + this class' TIME_TO_LIVE setting. 
* 
* @param cacheKey 
* @param object 
*/ 
public static void storeObjectInCache(String cacheKey, Object object) { 
    Date expirationDate = new Date(System.currentTimeMillis() + TIME_TO_LIVE); 
    Element e = new Element(object, expirationDate); 
    cacheMap.put(cacheKey, e); 
} 

/** 
* Stores an object in the cache, wrapped by an Element object. 
* The Element object has an expiration date, which will be set to 
* now + the timeToLiveInMilliseconds value that is passed into the method. 
* 
* @param cacheKey 
* @param object 
* @param timeToLiveInMilliseconds 
*/ 
public static void storeObjectInCache(String cacheKey, Object object, int timeToLiveInMilliseconds) { 
    Date expirationDate = new Date(System.currentTimeMillis() + timeToLiveInMilliseconds); 
    Element e = new Element(object, expirationDate); 
    cacheMap.put(cacheKey, e); 
} 

public static void removeCacheItem(String cacheKey) { 
    cacheMap.remove(cacheKey); 
} 

public static void clearCache() { 
    cacheMap.clear(); 
} 

static class Element { 

    private Object object; 
    private Date expirationDate; 

    /** 
    * @param object 
    * @param key 
    * @param expirationDate 
    */ 
    private Element(Object object, Date expirationDate) { 
     super(); 
     this.object = object; 
     this.expirationDate = expirationDate; 
    } 
    /** 
    * @return the object 
    */ 
    public Object getObject() { 
     return object; 
    } 
    /** 
    * @param object the object to set 
    */ 
    public void setObject(Object object) { 
     this.object = object; 
    } 
    /** 
    * @return the expirationDate 
    */ 
    public Date getExpirationDate() { 
     return expirationDate; 
    } 
    /** 
    * @param expirationDate the expirationDate to set 
    */ 
    public void setExpirationDate(Date expirationDate) { 
     this.expirationDate = expirationDate; 
    } 
} 
} 

PERO !!!! A partir de 01/2012, The RestTemplate in Spring Android no le da acceso para agregar un HttpContext a la ejecución de la solicitud. Esto se está solucionando en Spring Framework 3.1.0.RELEASE y esa solución es scheduled to be migrated into Spring Android 1.0.0.RC1.

Por lo tanto, cuando obtengamos Spring Android 1.0.0.RC1, deberíamos poder agregar el contexto como se describe en el ejemplo anterior. Hasta entonces, debemos agregar/extraer las cookies de los encabezados de solicitud/respuesta usando un ClientHttpRequestInterceptor.

public class MyClientHttpRequestInterceptor implements 
    ClientHttpRequestInterceptor { 

private static final String SET_COOKIE = "set-cookie"; 
private static final String COOKIE = "cookie"; 
private static final String COOKIE_STORE = "cookieStore"; 

/* (non-Javadoc) 
* @see org.springframework.http.client.ClientHttpRequestInterceptor#intercept(org.springframework.http.HttpRequest, byte[], org.springframework.http.client.ClientHttpRequestExecution) 
*/ 
@Override 
public ClientHttpResponse intercept(HttpRequest request, byte[] byteArray, 
     ClientHttpRequestExecution execution) throws IOException { 

    Log.d(getClass().getSimpleName(), ">>> entering intercept"); 
    List<String> cookies = request.getHeaders().get(COOKIE); 
    // if the header doesn't exist, add any existing, saved cookies 
    if (cookies == null) { 
     List<String> cookieStore = (List<String>) StaticCacheHelper.retrieveObjectFromCache(COOKIE_STORE); 
     // if we have stored cookies, add them to the headers 
     if (cookieStore != null) { 
      for (String cookie : cookieStore) { 
       request.getHeaders().add(COOKIE, cookie); 
      } 
     } 
    } 
    // execute the request 
    ClientHttpResponse response = execution.execute(request, byteArray); 
    // pull any cookies off and store them 
    cookies = response.getHeaders().get(SET_COOKIE); 
    if (cookies != null) { 
     for (String cookie : cookies) { 
      Log.d(getClass().getSimpleName(), ">>> response cookie = " + cookie); 
     } 
     StaticCacheHelper.storeObjectInCache(COOKIE_STORE, cookies); 
    } 
    Log.d(getClass().getSimpleName(), ">>> leaving intercept"); 
    return response; 
} 

} 

El intercepter intercepta la solicitud, busca en la caché para ver si hay algún cookies para agregar a la solicitud, a continuación, ejecuta la solicitud, luego saca las cookies de la respuesta y los almacena para uso futuro.

Añadir el interceptor a la plantilla de solicitud:

restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(HttpClientHelper.createDefaultHttpClient(GET_SERVICE_URL))); 
ClientHttpRequestInterceptor[] interceptors = {new MyClientHttpRequestInterceptor()}; 
restTemplate.setInterceptors(interceptors); 

Y hay que ir! Lo probé y funciona. Eso debería mantenerte hasta Spring Android 1.0.0.RC1 cuando podamos usar el HttpContext directamente con RestTemplate.

¡Espero que esto ayude a los demás!

Cuestiones relacionadas