我的应用程序从使用基于表单的身份验证的网站中提取数据。它需要透明地响应重定向到登录页面并通过 POST 请求提供请求的凭据。
我以前使用过 ASIHTTPREQUEST,然后通过检查 url 的过程来查看我是否已被重定向到身份验证页面,如果是,则使用登录表单变量发送 POST 请求,然后再次发出原始请求。它可以工作,但有点破解。
我目前正在将我的代码移至 AFNetworking 并想知道是否有更优雅的方式来实现这一点,也许注入一个 auth 标头?当重定向到身份验证页面时,让 AFHTTPClient 触发身份验证委托方法,然后发布表单。下面是一段伪代码:
- (void)requestFinished:(ASIHTTPRequest *)request {
if ([Connection isAuthURL:[request url]])
{
// If so have we just tried to login ?
if ( requestState == requestStateSendingLoginCredentials )
{
// Login Failed - tried to login & been redirected back to login page
[self requestFailed:request];
}
else
{
// We have been directed to login page after a page request
requestState = requestStateSendingLoginCredentials
[self postLoginForm:request];
}
}
else
{ // Not the authentication page
if ( requestState == requestStateSendingLoginCredentials )
{ // We must have successfully logged in
requestState = requestStateSuccessful;
// If it was a form we need to post again now were logged in.
if ([lastRequest isAForm])
{
// If original request that triggered the login was a POST request
// we have to re-send it.
[self requestURL:nil]; // This will send the last request again
return;
}
}
if (requestState == requestStateSuccessful)
{
[self processResponse:request];
}
}