簡介背景故事,我們以前的開發人員使用ASIHTTPRequest來發出POST請求並從我們的web服務中檢索數據。原因未知我們的應用程序的這部分停止工作。似乎有足夠的時間來證明未來,並與AFNetworking合作。 REST webservice在CakePHP框架上運行。AFNetworking POST到REST webservice
總之,我沒有收到使用AFNetworking的請求響應字符串。
我知道web服務工作,因爲我能夠成功發佈的數據,並使用得到適當的響應捲曲: 捲曲-d「數據[產品型號] [field0] = field0value &數據[產品型號] [字段1] = field1value」 https://example.com/api/class/function.plist
根據以前的開發人員的指示,我想出了以下內容。
#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];
}
輸出: 操作hasAcceptableStatusCode:200 響應字符串:空白plist文件
嘗試的解決方案1: AFNetworking Post Request 所提出的解決方案使用AFHTTPRequestOperation的函數調用operationWithRequest。但是,當我嘗試使用所述解決方案時,我收到警告「類方法」+ operationWithRequest:完成:'未找到(返回類型默認爲'id'「
嘗試解決方案2:NSURLConnection。output:打印傳遞消息的成功日誌,但不響應字符串 *更新 - 。返回空白的plist
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSString *httpBodyData = @"data[User][email][email protected]&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");
}
你好,Pouria,你嘗試使用NSURLConnection發送同步請求嗎? – 8vius 2012-03-29 15:17:14
嘗試解決方案2:我是如何嘗試NSURLConnection。 – Airuop 2012-03-29 17:20:56
服務器端的所有設置是否正確?像擴展解析一樣,響應的佈局和它們的視圖?看起來更像是一個服務器問題,而不是客戶端問題。 – 8vius 2012-03-29 19:08:18