Spring Android:使用RestTemplate和https以及cookie

时间:2011-08-18 02:17:07

标签: android spring resttemplate

我需要在Android本机应用的https连接上使用Cookie。 我正在使用RestTemplate。

检查其他主题 (例如Setting Security cookie using RestTemplate) 我能够在http连接中处理cookie:

restTemplate.setRequestFactory(new YourClientHttpRequestFactory());

其中YourClientHttpRequestFactory extends SimpleClientHttpRequestFactory

这适用于http但不适用于https。

另一方面,我能够解决Android信任SSL证书的https问题:

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

这里描述了HttpUtils: http://www.makeurownrules.com/secure-rest-web-service-mobile-application-android.html

我的问题是我需要使用ClientHttpRequestFactory的单个实现。 所以我有3个选择:

1)找到一种使用SimpleClientHttpRequestFactory

处理https的方法

2)找到一种使用HttpComponentsClientHttpRequestFactory处理cookie的方法

3)使用另一种方法

1 个答案:

答案 0 :(得分:8)

我遇到了同样的问题。这是我的解决方案:

首先,我以与您相同的方式处理SSL(我使用Bob Lee的方法)。

Cookies是另一回事。我在过去没有使用RestTemplate处理cookie的方式(即直接使用Apache的HttpClient类)是将HttpContext的实例传递给HttpClient的execute方法。我们退后一步......

HttpClient有许多重载execute方法,其中一个是:

execute(HttpUriRequest request, HttpContext context)

HttpContext的实例可以引用CookieStore。当您创建HttpContext的实例时,请提供CookieStore(新的CookieStore或您之前请求中保存的CookieStore):

    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;
}

当然,如果您愿意,可以在发送请求之前将Cookie添加到CookieStore实例。现在,当您调用execute方法时,请使用HttpContext的实例:

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

(其中httpRequester是HttpPost,HttpGet等的实例)

如果您需要在后续请求中重新发送任何cookie,请确保将cookie存储在某处:

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

此代码中使用的StaticCacheHelper类只是一个可以在静态Map中存储数据的自定义类:

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;
    }
}
}

BUT !!!!截至2012年1月,Android中的RestTemplate Android不允许您在执行请求时添加HttpContext!这在Spring Framework 3.1.0.RELEASE中得到修复,修复版本为scheduled to be migrated into Spring Android 1.0.0.RC1

因此,当我们获得Spring Android 1.0.0.RC1时,我们应该能够添加上面示例中描述的上下文。在此之前,我们必须使用ClientHttpRequestInterceptor从请求/响应头添加/拉取cookie。

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;
}

}

拦截器拦截请求,在缓存中查找是否有任何cookie添加到请求中,然后执行请求,然后从响应中提取任何cookie并存储它们以备将来使用。

将拦截器添加到请求模板中:

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

你去吧!我测试了它,它的工作原理。当我们可以直接使用HttpContext与RestTemplate时,这应该让你坚持到Spring Android 1.0.0.RC1。

希望这有助于其他人!!