AFNetworking POST到REST webservice [英] AFNetworking POST to REST webservice

查看:134
本文介绍了AFNetworking POST到REST webservice的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单的说,我们以前的开发人员使用ASIHTTPRequest来做POST请求和从我们的web服务检索数据。由于未知的这个部分我们的应用程序停止工作的原因。似乎足够好的时间未来的证明,去与AFNetworking。 REST webservice在CakePHP框架上运行。



总之,我没有收到使用AFNetworking的请求响应字符串。



我知道webservice的工作原理,因为我能够成功发布数据和接收正确的响应使用curl:
curl -ddata [Model] [field0 ] = field0value& data [Model] [field1] = field1value https://example.com/api/class/function。 plist



根据以前开发人员的说明,我想出了以下内容。

  #importAFHTTPRequestOperation.h

...

- IBAction)loginButtonPressed {

NSURL * url = [NSURL URLWithString:@https://example.com/api/class/function.plist];

NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];

[request setHTTPMethod:@POST];

[request setValue:@application / x-www-form-urlencodedforHTTPHeaderField:@Content-Type];

[request setValue:[usernameTextField text] forHTTPHeaderField:@data [User] [email]];

[request setValue:[passwordTextField text] forHTTPHeaderField:@data [User] [password]];

AFHTTPRequestOperation * operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation * operation,id responseObject){

NSLog(@operation hasAcceptableStatusCode:%d,[operation.response statusCode]);

NSLog(@response string:%@,operation.responseString);

}失败:^(AFHTTPRequestOperation * operation,NSError * error){

NSLog(@error:%@,operation.responseString);

}];

[operation start];

}

输出:
operation hasAcceptableStatusCode:200
响应字符串:一个空白plist文件



尝试解决方案1:
AFNetworking Post Request
提出的解决方案使用一个称为operationWithRequest的AFHTTPRequestOperation函数。但是,当我尝试使用所述解决方案时,我得到一个警告类方法'+ operationWithRequest:完成:'未找到(返回类型默认为'id'



<解决方案2:NSURLConnection输出:我能够打印成功日志消息,但不能打印响应字符串
* update - 返回空白plist。

  NSMutableURLRequest * req = [NSMutableURLRequest requestWithURL:url]; 
NSString * httpBodyData = @data [User] [email] = username@example.com& data [User] = awesomepassword;
[httpBodyData dataUsingEncoding:NSUTF8StringEncoding];
[req setHTTPMethod:@POST];
[req setHTTPBody:[NSData dataWithContentsOfFile:httpBodyData]];
NSHTTPURLResponse __autoreleasing * response;
NSError __autoreleasing * error;
[NSURLConnection sendSynchronousRequest:req returningResponse:& response error:& error];

// * update -
NSData * responseData = [NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];
NSString * str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@responseData%@,str);

if(error == nil&& response.statusCode == 200){
//处理响应
NSLog(@success); //返回成功代码为200,但为空
NSLog(@resp%@,response);
} else {
//进程错误
NSLog(@error);
}


解决方案

我为自己的使用)线,最终满足我的请求到Web服务。感谢您的建议@ 8vius and @mattt!

   - (IBAction)loginButtonPressed {
NSURL * baseURL = [NSURL URLWithString:@https://www.example.com/api/class];

//构建正常的NSMutableURLRequest对象
//确保将HTTPMethod设置为POST。
//从https://github.com/AFNetworking/AFNetworking
AFHTTPClient * httpClient = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
[httpClient defaultValueForHeader:@Accept];

NSDictionary * params = [NSDictionary dictionaryWithObjectsAndKeys:
[usernameTextField text],kUsernameField,
[passwordTextField text],kPasswordField,
nil];

NSMutableURLRequest * request = [httpClient requestWithMethod:@POST
path:@https://www.example.com/api/class/functionparameters:params];

//将您的请求对象添加到AFHTTPRequestOperation
AFHTTPRequestOperation * operation = [[[AFHTTPRequestOperation alloc]
initWithRequest:request] autorelease];

//为什么我的HTTP客户端回调中没有JSON / XML / Property List?
// see:https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ
// mattt的建议http://stackoverflow.com/a/9931815/1004227 -
// - 仍然没有阻止我接收plist数据
// [httpClient registerHTTPOperationClass:
// [AFPropertyListParameterEncoding class]];

[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];

[operation setCompletionBlockWithSuccess:
^(AFHTTPRequestOperation * operation,
id responseObject){
NSString * response = [operation responseString];
NSLog(@response:[%@],response);
}失败:^(AFHTTPRequestOperation * operation,NSError * error){
NSLog(@error:%@,[operation error]);
}];

//调用请求操作的开始
[operation start];
[httpClient release];
}


Brief backstory, our previous developer used ASIHTTPRequest to make POST requests and retrieve data from our webservice. For reasons unknown this portion of our app stopped working. Seemed like good enough time to future proof and go with AFNetworking. REST webservice runs on the CakePHP framework.

In short I am not receiving the request response string using AFNetworking.

I know the webservice works because I am able to successfully post data and receive the proper response using curl: curl -d "data[Model][field0]=field0value&data[Model][field1]=field1value" https://example.com/api/class/function.plist

Per the previous developer's instructions I came up with the following.

#import "AFHTTPRequestOperation.h"    

…

- (IBAction)loginButtonPressed {

    NSURL *url = [NSURL URLWithString:@"https://example.com/api/class/function.plist"];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    [request setHTTPMethod:@"POST"];

    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    [request setValue:[usernameTextField text] forHTTPHeaderField:@"data[User][email]"];

    [request setValue:[passwordTextField text] forHTTPHeaderField:@"data[User][password]"];

    AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {  

        NSLog(@"operation hasAcceptableStatusCode: %d", [operation.response statusCode]);

        NSLog(@"response string: %@ ", operation.responseString);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        NSLog(@"error: %@", operation.responseString);

    }];

    [operation start];

}

output: operation hasAcceptableStatusCode: 200 response string: a blank plist file

attempted solution 1: AFNetworking Post Request the proposed solution uses a function of AFHTTPRequestOperation called operationWithRequest. However, when I attempt to use said solution I get a warning "Class method '+operationWithRequest:completion:' not found (return type defaults to 'id'"

attempted solution 2: NSURLConnection. output: I'm able to print the success log messaged but not the response string. *update - returns blank plist.

NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSString *httpBodyData = @"data[User][email]=username@example.com&data[User][password]=awesomepassword";
[httpBodyData dataUsingEncoding:NSUTF8StringEncoding];
[req setHTTPMethod:@"POST"];
[req setHTTPBody:[NSData dataWithContentsOfFile:httpBodyData]];
NSHTTPURLResponse __autoreleasing *response;
NSError __autoreleasing *error;
[NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];

// *update - returns blank plist
NSData *responseData = [NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];
NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"responseData %@",str);

if (error == nil && response.statusCode == 200) {
    // Process response
    NSLog(@"success");//returns success code of 200 but blank
    NSLog(@"resp %@", response );
} else {
    // Process error
    NSLog(@"error");
}

解决方案

These are the essential (stripping out conditions I've made for my own use) lines that ended up satisfying my request to the web service. Thanks for the suggestions @8vius and @mattt !

- (IBAction)loginButtonPressed {        
    NSURL *baseURL = [NSURL URLWithString:@"https://www.example.com/api/class"];

    //build normal NSMutableURLRequest objects
    //make sure to setHTTPMethod to "POST". 
    //from https://github.com/AFNetworking/AFNetworking
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
    [httpClient defaultValueForHeader:@"Accept"];

    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                            [usernameTextField text], kUsernameField, 
                            [passwordTextField text], kPasswordField, 
                            nil];

    NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" 
          path:@"https://www.example.com/api/class/function" parameters:params];

    //Add your request object to an AFHTTPRequestOperation
    AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] 
                                      initWithRequest:request] autorelease];

    //"Why don't I get JSON / XML / Property List in my HTTP client callbacks?"
    //see: https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ
    //mattt's suggestion http://stackoverflow.com/a/9931815/1004227 -
    //-still didn't prevent me from receiving plist data
    //[httpClient registerHTTPOperationClass:
    //         [AFPropertyListParameterEncoding class]];

    [httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];

    [operation setCompletionBlockWithSuccess:
      ^(AFHTTPRequestOperation *operation, 
      id responseObject) {
        NSString *response = [operation responseString];
        NSLog(@"response: [%@]",response);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error: %@", [operation error]);
    }];

    //call start on your request operation
    [operation start];
    [httpClient release];
}

这篇关于AFNetworking POST到REST webservice的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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