HTTPClient(); を使用して Web サイトにログインしたい。リダイレクトをたどることができません(例外があります)。
クライアントと 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);
そして、私の GetPage メソッドで、次のリダイレクトを実行します。
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;
}
そして私のシェル結果:
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
どうすればリダイレクトをたどることができますか?
PS:私が使用する場合:
myMethod.setFollowRedirects(true);
私は別の例外があります:
java.lang.IllegalArgumentException: Entity enclosing requests cannot be redirected without user intervention