Eviter l’exception « Too many redirects at URL » sur Google App Engine
Salut,
Ce soir, je vous fais part d’une petite « astuce » qui m’a permis de surpasser les limitations de Google App Engine en matière de redirection. En effet, l’utilisation du service URLFecthService ne supporte pas les pages web avec plus de 5 redirections.
Du coup, j’ai mis au point un petit bout de code pour passer outre cette limitation.
package com.roisoleil.redirectexception;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import com.google.appengine.api.urlfetch.FetchOptions.Builder;
import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;
public class RedirectUtils {
public final static String LOCATION = "Location";
public final static int REDIRECT_CODE = 301;
public final static int REDIRECT_CODE_2 = 302;
public static URL resolveRedirect(URL url, HTTPMethod httpMethod)
throws IOException {
URL resolvedURL = url;
URLFetchService urlFetchService = URLFetchServiceFactory
.getURLFetchService();
HTTPResponse httpResponse = urlFetchService.fetch(new HTTPRequest(url,
httpMethod, Builder.doNotFollowRedirects()));
if (REDIRECT_CODE == httpResponse.getResponseCode()
|| REDIRECT_CODE_2 == httpResponse.getResponseCode()) {
String location = getLocation(httpResponse.getHeaders());
resolvedURL = resolveRedirect(new URL(location), httpMethod);
}
return resolvedURL;
}
public static String getLocation(List httpHeaders) {
HTTPHeader locationHeader = null;
for (HTTPHeader httpHeader : httpHeaders) {
if (LOCATION.equals(httpHeader.getName())) {
locationHeader = httpHeader;
break;
}
}
return locationHeader.getValue();
}
}
Le code ne fait que « Fetcher » l’URL souhaitée sans suivre la possible redirection et si il y a redirection continue jusqu’à avoir l’adresse finale.
Pour faire mes tester, j’ai créé une application à cette URL qui permet de tester mon code.
Avec qui fait une boucle de redirection
Avec qui fais appel directiement à URLFecthService
et qui fait appel à mon code avant de faire appel à URLFetchService
Voilà … en espérant que cela aide 😉