Je souhaite me connecter à un site Web avec HTTPClient(); et je ne peux pas suivre la redirection (j'ai une exception).HTTPCLIENT: isRedirectNeeded
Je crée mon client et hostconfig:
client = new HttpClient();
client.getParams().setParameter(HttpMethodParams.USER_AGENT, useragent);
client.getParams().setParameter(HttpMethodParams.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
client.getParams().setParameter("http.protocol.allow-circular-redirects", true);
client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
[...]
HostConfiguration hostConfig = client.getHostConfiguration();
hostConfig.setHost(new URI(url, true));
PostMethod post = new PostMethod(login);
post.addParameter("username", pseudo);
post.addParameter("password", password);
post.addParameter("secure_login", tooken);
getPage(client, post, hostConfig);
Et dans ma GetPage Méthode, j'execute redirect suit:
public String getPage(HttpClient myClient, PostMethod myMethod, HostConfiguration hostConfig) {
[...]
try {
// execute methode
int returnCode = myClient.executeMethod(hostConfig, myMethod);
// handle redirection
if (returnCode == HttpStatus.SC_MOVED_TEMPORARILY
|| returnCode == HttpStatus.SC_MOVED_PERMANENTLY
|| returnCode == HttpStatus.SC_SEE_OTHER
|| returnCode == HttpStatus.SC_TEMPORARY_REDIRECT) {
System.out.println("Redirection encountered:" + returnCode);
String redirectLocation = null;
Header locationHeader = myMethod.getResponseHeader("location");
if (locationHeader != null) {
redirectLocation = locationHeader.getValue();
} else {
System.err.println("ERROR : 01");
}
if (redirectLocation != null) {
System.out.println("redirectLocation : "+redirectLocation);
hostConfig.setHost(new URI(url + redirectLocation, true));
GetMethod redirect = new GetMethod(url + redirectLocation);
returnCode = myClient.executeMethod(hostConfig, redirect);
}
}
// Handle redirects
else if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
[...]
} else {
// get Result in String
}
}
} catch (Exception e) {
System.err.println(e);
} finally {
myMethod.releaseConnection();
if (br != null) {
try {
br.close();
} catch (Exception fe) {
}
}
}
return retval;
}
Et mon résultat shell:
Redirection encountered:302
redirectLocation : /?section=INDEX
juil. 20, 2013 12:16:07 PM org.apache.commons.httpclient.HttpMethodDirector isRedirectNeeded
INFO: Redirect requested but followRedirects is disabled
Comment i peut suivre la redirection?
PS: si j'utiliser:
myMethod.setFollowRedirects(true);
j'ai une autre exception:
java.lang.IllegalArgumentException: Entity enclosing requests cannot be redirected without user intervention
[http: // stackoverflow .com/questions/3091053/how-to-connexion en site Web utilisant java] [1] Commander la réponse ci-dessus pour q uestion. Cela peut vous aider. [1]: http://stackoverflow.com/questions/3091053/how-to-login-in-web-site-using-java –