我的應用程序從使用基於表單的身份驗證的網站提取數據。它需要透明地對重定向做出反應,以便通過POST請求提供所請求的憑證,登錄頁面爲&。我以前用過ASIHTTPREQUEST &使用AFHTTPClient進行Cookie身份驗證
然後通過檢查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];
}
}
問題是我沒有得到401認證。重定向到登錄頁面後,我得到一個200。如何在發生這種情況時觸發'AFURLConnection -setAuthenticationChallengeBlock:'來觸發? – lidders
那麼,認證回調只有在服務器發送認證應該發生的任何指示時才起作用。也許你可以使用[剛添加的重定向響應塊屬性](https://github.com/AFNetworking/AFNetworking/commit/d17b2998d7d7c877a3133959c97498780e064681),通過提供一個鉤子來掛鉤重定向。 – mattt
無論哪種方式,因爲如果您有能力更改服務器後端或使用適當的API,那會讓事情變得更容易。 – mattt