NSMutableURLRequest正确发布 [英] NSMutableURLRequest proper posting

查看:62
本文介绍了NSMutableURLRequest正确发布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想尝试使用NSMutableURLRequest登录我的网站,NSMutableURLRequest通过帖子显示凭据。作为一个noobie,我对这个方法的功能有一些疑问,以确保我理解它。

So I am trying to log into my site using an NSMutableURLRequest which presents the credentials via a post. As a noobie, I have some questions about the functionality of this method to make sure I am understanding it.

NSString *post = [NSString stringWithFormat:@"username=%@&password=%@&TARGET=%@",LoginId,LoginPwd,target];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setHTTPShouldHandleCookies:YES];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://somelogin.mycomp.verify.fcc"]]];
//[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
[request setHTTPBody:postData];

NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];

现在这将通过委托方法自动处理任何重定向吗?它还会收集任何饼干吗?另外,我应该使用异步请求吗?谢谢!

Now this will automatically handle any redirects via the delegate method correct? It will also collect any cookies along the way? Also, should I be using an asynchronous request instead? Thanks!

更新:
所以我推断出一些cookie被请求和后续重定向忽略了。有谁知道为什么会发生这种情况?

UPDATE: So I have deduced that some of the cookies are being ignored by the request and subsequent redirects. Does anyone know why that may be happening?

推荐答案

你可以在同步登录时做同样的事......代码是不完美,但这是一般的想法。

you can do something like this when logging in synchronously... the code is not perfect, but this is the general idea.

在这里查看文档

https:// developer.apple.com/library/content/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/AuthenticationChallenges.html#//apple_ref/doc/uid/TP40009507-SW1

// credentials set here
NSURLCredential *creds = [NSURLCredential credentialWithUser:LoginId password:LoginPwd
                                           persistence:NSURLCredentialPersistenceForSession];

NSURLProtectionSpace *protectionedSpace = [[NSURLProtectionSpace alloc]
  initWithHost:@"mycomp.verify.fcc"
  port:8443
  protocol:@"https"
  realm:nil
  authenticationMethod:nil];


[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:creds
                                            forProtectionSpace:protectionedSpace];

// removed credentials from line...
NSString *post = [NSString stringWithFormat:@"TARGET=%@",target];

这是一个异步执行的教程

here is a tutorial that does it asynchronously

http://iosdevelopertips.com/网络/处理 - 网址 - 身份验证 - 挑战 - 访问密码 - 受保护的服务器

这篇关于NSMutableURLRequest正确发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆