通缉:使用AFNetworking-2进行基本身份验证的JSON / POST的最新示例 [英] Wanted: Up-to-date example for JSON/POST with basic auth using AFNetworking-2

查看:92
本文介绍了通缉:使用AFNetworking-2进行基本身份验证的JSON / POST的最新示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个玩具应用程序,使用基本身份验证安全性提交https JSON / POST。我被告知我应该考虑使用AFNetworking。我已经能够将AFNetwork-2安装到我的XCode项目(ios7目标,XCode5)中。但是这些例子似乎都与当前版本的AFNetworking-2无关,而是与以前的版本相关。 AFNetworking的文档相当稀疏,所以我正在努力将各个部分放在一起。非AFNetworking代码类似于:

I have a toy app which submits an https JSON/POST using basic auth security. I've been told I should consider using AFNetworking. I've been able to install AFNetwork-2 into my XCode project (ios7 target, XCode5) just fine. But none of the examples out there seem to be relevant to current versions of AFNetworking-2, but rather previous versions. The AFNetworking docs are pretty sparse, so I'm struggling how to put the pieces together. The non-AFNetworking code looks something like:

NSURL *url = [NSURL URLWithString:@"https://xxx.yyy.zzz.aaa:bbbbb/twig_monikers"];
NSMutableURLRequest *request = [NSMutableURLRequest
    requestWithURL:url
    cachePolicy: NSURLRequestUseProtocolCachePolicy
    timeoutInterval: 10.0];

NSData *requestData = [NSJSONSerialization dataWithJSONObject: [self jsonDict] options: 0 error: nil];
[request setHTTPMethod: @"POST"];
[request setValue: @"application/json" forHTTPHeaderField: @"Accept"];
[request setValue: @"application/json" forHTTPHeaderField: @"Content-Type"];
[request setValue:[NSString stringWithFormat: @"%d", [requestData length]] forHTTPHeaderField: @"Content-Length"];
NSData *plainPassText = [@"app_pseudouser:sample_password" dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64PassText = [plainPassText base64EncodedStringWithOptions: NSDataBase64Encoding76CharacterLineLength];
[request setValue:[NSString stringWithFormat: @"Basic %@", base64PassText] forHTTPHeaderField: @"Authorization"];

FailedCertificateDelegate *fcd=[[FailedCertificateDelegate alloc] init];
NSURLConnection *c=[[NSURLConnection alloc] initWithRequest:request delegate:fcd startImmediately:NO];
[c setDelegateQueue:[[NSOperationQueue alloc] init]];
[c start];
NSData *data=[fcd getData];

if (data)
    NSLog(@"Submit response data: %@", [NSString stringWithUTF8String:[data bytes]]);

我不是在寻找有人为我编写代码。我似乎无法弄清楚如何将AFNetworking-2部分映射到那个部分。任何链接,示例或解释都非常欢迎。

I'm not looking for someone to write my code for me. I just can't seem to figure out how to map the AFNetworking-2 parts over to that. Any links, or examples, or explanations much welcome.

更新1

以上是已知有效的非AF版本。我试图一次性完成所有操作,我只是尝试了:

The above is a non AF version that is known to work. Moving trying to get it all in one go, I just tried:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer
    setAuthorizationHeaderFieldWithUsername:@"app_pseudouser"
    password:@"sample_password"];
AFHTTPRequestOperation *operation =
[manager
    PUT: @"https://172.16.214.214:44321/twig_monikers"
    parameters: [self jsonDict]
    success:^(AFHTTPRequestOperation *operation, id responseObject){
        NSLog(@"Submit response data: %@", responseObject);}
    failure:^(AFHTTPRequestOperation *operation, NSError *error){
        NSLog(@"Error: %@", error);}
];

产生以下错误:

2013-10-09 11:41:38.558 TwigTag[1403:60b] Error: Error Domain=NSURLErrorDomain Code=-1012 "The operation couldn’t be completed. (NSURLErrorDomain error -1012.)" UserInfo=0x1662c1e0 {NSErrorFailingURLKey=https://172.16.214.214:44321/twig_monikers, NSErrorFailingURLStringKey=https://172.16.214.214:44321/twig_monikers}

在服务器端看,没有任何东西可以通过。我不知道是不是因为https,或者是什么,但是我可以将应用程序翻转回原始代码,并且通过就好了。

Watching on the server side, nothing ever makes it through. I don't know if it is because the https, or what, but I can flip the app back to the original code, and it gets through just fine.

推荐答案

更新:发现以下JSON部分适用于PUT / POST,但不适用于GET / HEAD / DELETE

UPDATE: The JSON portion of the following was found to work for PUT/POST, but NOT for GET/HEAD/DELETE

之后一些争吵,外面的帮助,我有一些工作,我想留下作为纪念品。最后,AFNetworking-2给我留下了非常深刻的印象。这很简单,我一直试图让它变得比以前更难。给定一个返回要发送的json数据包的 jsonDict 方法,我创建了以下内容:

After some wrangling, and help outside SO, I got something working, which I wanted to leave as a memento. In the end, I was really very impressed with AFNetworking-2. It was so simple, I kept trying to make it harder than it should have been. Given a jsonDict method that returns the json packet to send, I created the following:

- (void) submitAuthenticatedRest_PUT
{
    // it all starts with a manager
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    // in my case, I'm in prototype mode, I own the network being used currently,
    // so I can use a self generated cert key, and the following line allows me to use that
    manager.securityPolicy.allowInvalidCertificates = YES;
    // Make sure we a JSON serialization policy, not sure what the default is
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    // No matter the serializer, they all inherit a battery of header setting APIs
    // Here we do Basic Auth, never do this outside of HTTPS
    [manager.requestSerializer
        setAuthorizationHeaderFieldWithUsername:@"basic_auth_username"
        password:@"basic_auth_password"];
    // Now we can just PUT it to our target URL (note the https).
    // This will return immediately, when the transaction has finished,
    // one of either the success or failure blocks will fire
    [manager
        PUT: @"https://101.202.303.404:5555/rest/path"
        parameters: [self jsonDict]
        success:^(AFHTTPRequestOperation *operation, id responseObject){
            NSLog(@"Submit response data: %@", responseObject);} // success callback block
        failure:^(AFHTTPRequestOperation *operation, NSError *error){
            NSLog(@"Error: %@", error);} // failure callback block
    ];
}

3个设置语句,然后是2个消息发送,真的很容易。

3 setup statements, followed by 2 message sends, it really is that easy.

编辑/添加:这是一个示例@jsonDict实现:

EDIT/ADDED: Here's an example @jsonDict implementation:

- (NSMutableDictionary*) jsonDict
{
    NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
    result[@"serial_id"] = self.serialID;
    result[@"latitude"] = [NSNumber numberWithDouble: self.location.latitude];
    result[@"longitude"] = [NSNumber numberWithDouble: self.location.longitude];
    result[@"name"] = self.name;
    if ([self hasPhoto])
    {
        result[@"photo-jpeg"] = [UIImageJPEGRepresentation(self.photo, 0.5)
            base64EncodedStringWithOptions: NSDataBase64Encoding76CharacterLineLength];
}
return result;

}

它应该只返回一个带有字符串键的字典,以及作为值的简单对象(NSNumber,NSString,NSArray(我认为)等)。 JSON编码器为您完成剩下的工作。

It should just return a dictionary with string keys, and simple objects as values (NSNumber, NSString, NSArray (I think), etc). The JSON encoder does the rest for you.

这篇关于通缉:使用AFNetworking-2进行基本身份验证的JSON / POST的最新示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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