- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的问题是采用 [NSURLConnection sendAsynchronousRequest...]
和 POST
方法在 iOS7 上失败但在 iOS6 环境下成功。
其他信息:
在我的 iOS6 环境中可以像这样从服务器获取 JSON 数据。 (成功)
{
"status": 200,
"data": [
{
"oauth_token": "BVgOa01tg6JvfuXOPoJS8wB26TpvAaDs"
}
]
}
iOS7 上的相同代码会收到此错误消息。 (失败)
error:Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (No value.)
我检查了服务器端的 PHP 代码,发现服务器可以从 iOS6 POST 数据中获取数据,但无法从 iOS7 中获取 POST 数据。 (同样的代码不同的结果,很奇怪。)
有没有人可以帮助我或给我建议?多谢。
- (void) apiLogin
{
NSDictionary *params = @{@"client_id" : @"1234567",
@"response_type" : @"token",
@"redirect_uri" : @"/oauth2-php/server/examples/pdo/",
@"state" : @"test_state",
@"scope" : @"",
@"accept" : @"Yep",
@"uid" : uid,
@"pwd" : withPwd};
NSData *postDataString = [self dataForHTTPPost:params];
// Server API 位置
NSURL *url=[NSURL URLWithString:@"http://xxx.xxx.tw/xxx.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:120];
[request setURL:url];
// Solution3:
NSString *postLength = [NSString stringWithFormat:@"%d", [postDataString length]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postDataString];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
NSLog(@"D1: responseCode: %d", responseCode);
if (!connectionError && responseCode == 200) {
// 採用Apple官方方法將 來源轉成JSON Format並交由NSDictionary 接手.
NSError *localError = nil;
NSLog(@"data:%@", data);
NSDictionary *allInDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&localError];
NSLog(@"Source:%@", allInDic);
NSLog(@"error:%@", localError);
// 取出oauth_token資料
if ([[allInDic objectForKey:@"status"] integerValue] == 200) {
// 將新取得之 oauth_token 寫入DB
NSArray * dataArray = [allInDic objectForKey:@"data"];
NSDictionary *responseData = [dataArray objectAtIndex:0];
NSString *t = [responseData objectForKey:@"oauth_token"];
[helper setDbOauthToken:nil :t :TABLE_USER_PROFILES];
NSLog(@"(API-New)oauth_token:%@", t);
} else
{
NSLog(@"connectionError=%@", connectionError);
NSLog(@"responseCode=%d", responseCode);
}
}
}];
}
- (NSData *)dataForHTTPPost:(NSDictionary*) parms
{
NSMutableArray *array = [NSMutableArray array];
for (NSString *key in parms) {
id obj = [parms objectForKey:key];
NSString *valueString;
if ([obj isKindOfClass:[NSString class]])
valueString = obj;
else if ([obj isKindOfClass:[NSNumber class]])
valueString = [(NSNumber *)obj stringValue];
else if ([obj isKindOfClass:[NSURL class]])
valueString = [(NSURL *)obj absoluteString];
else
valueString = [obj description];
[array addObject:[NSString stringWithFormat:@"%@=%@", key, valueString]];
}
NSString *postString = [array componentsJoinedByString:@"&"];
NSLog(@"New2a HTTPPost Data:%@", postString);
return [postString dataUsingEncoding:NSUTF8StringEncoding];
}
- (IBAction)loginAction:(id)sender {
[self apiLogin];
}
New2a HTTPPost Data:response_type=token&uid=xxx&accept=Yep&scope=&client_id=1234567&state=test_state&redirect_uri=/oauth2-php/server/examples/pdo/&pwd=xxx
D1: responseCode: 200
data:<7b227374 61747573 223a3230 302c2264 61746122 3a5b7b22 6f617574 685f746f 6b656e22 3a224870 47366546 4b304a37 38434343 54306352 506e4d77 62544d5c 2f455631 32793422 7d5d7d>
Source:{
data = (
{
"oauth_token" = "HpG6eFK0J78CCCT0cRPnMwbTM/EV12y4";
}
);
status = 200;
}
error:(null)
(API-New)oauth_token:HpG6eFK0J78CCCT0cRPnMwbTM/EV12y4
New2a HTTPPost Data:response_type=token&uid=&accept=Yep&scope=&client_id=1234567&state=test_state&redirect_uri=/oauth2-php/server/examples/pdo/&pwd=
D1: responseCode: 200
data:<>
Source:(null)
error:Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (No value.) UserInfo=0x8a28d90 {NSDebugDescription=No value.}
connectionError=(null)
responseCode=200
NSString *uid = idField.text;
NSString *withPwd = pwdField.text;
// For testing Account ID
if (!uid||!withPwd) {
uid=@"xxx@gmail.com";
withPwd=@"xxxx";
}
NSLog(@"uid:%@ , pwd:%@", uid, withPwd);
// For testing Account ID
if ([uid isEqualToString:@""] || [withPwd isEqualToString:@""] ) {
uid=@"xxx@gmail.com";
withPwd=@"xxxx";
}
最佳答案
您正在记录数据
,但您可能想查看它的字符串表示形式。查看生成的字符串并查看来自服务器的响应中的内容。这样,如果您的服务器出现故障并返回一些非 JSON 错误消息,您可以看到字符串是什么。
同样,如果 connectionError
不是 nil
,您可能想要记录它。这里不是这种情况(否则,您不会获得当前的 NSLog
,但如果它不是 nil
,可能值得一看)。因此:
if (!connectionError && responseCode == 200) {
// 採用Apple官方方法將 來源轉成JSON Format並交由NSDictionary 接手.
if (data)
NSLog(@"data string: %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
else
NSLog(@"data is nil");
NSError *parseError = nil;
NSDictionary *allInDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&parseError];
NSLog(@"Source:%@", allInDic);
NSLog(@"error:%@", parseError);
// 取出oauth_token資料
if ([allInDic[@"status"] integerValue] == 200) {
// 將新取得之 oauth_token 寫入DB
NSArray * dataArray = allInDic[@"data"];
NSDictionary *responseDictionary = dataArray[0];
NSString *t = responseDictionary[@"oauth_token"];
[helper setDbOauthToken:nil :t :TABLE_USER_PROFILES];
NSLog(@"(API-New)oauth_token:%@", t);
}
}
else
{
NSLog(@"connectionError=%@", connectionError);
NSLog(@"responseCode=%d", responseCode);
}
我怀疑一旦您查看了您的数据
的字符串表示形式,问题就会变得不言而喻。
顺便说一句,这不太可能成为问题,但请确保您正确编码了要添加到 postData
的字符串。例如,如果您的密码包含符号、加号、空格或其他一些保留字符(如 RFC2396 的第 2.2 节中所述),您当前的代码将不起作用。您可能想申请 CFURLCreateStringByAddingPercentEscapes
添加到 postData
的值,例如,您可以像这样使用 NSString
类别:
@implementation NSString (URLPostEncode)
- (NSString *)stringForHTTPPost
{
NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)self,
(CFStringRef)@" ",
(CFStringRef)@";/?:@&=+$,",
kCFStringEncodingUTF8));
return [result stringByReplacingOccurrencesOfString:@" " withString:@"+"];
}
@end
我个人将其与以下 NSDictionary
类别结合起来:
@implementation NSDictionary (URLPostEncode)
- (NSData *)dataForHTTPPost
{
NSMutableArray *array = [NSMutableArray array];
[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSString *valueString;
if ([obj isKindOfClass:[NSString class]])
valueString = obj;
else if ([obj isKindOfClass:[NSNumber class]])
valueString = [(NSNumber *)obj stringValue];
else if ([obj isKindOfClass:[NSURL class]])
valueString = [(NSURL *)obj absoluteString];
else
valueString = [obj description];
[array addObject:[NSString stringWithFormat:@"%@=%@", key, [valueString stringForHTTPPost]]];
}];
NSString *postString = [array componentsJoinedByString:@"&"];
return [postString dataUsingEncoding:NSUTF8StringEncoding];
}
@end
有了这两个类别,我就可以做类似的事情:
NSDictionary *params = @{@"client_id" : client_id,
@"response_type" : response_type,
@"redirect_uri" : redirect_uri,
@"state" : state,
@"scope" : scope,
@"accept" : accept,
@"uid" : uid,
@"withPwd" : withPwd};
NSData *postData = [params dataForHTTPPost];
关于iphone - iOS7 NSURLConnection sendAsynchronousRequest 因 POST 数据而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19229491/
我的主 UI 线程调用 sendAsynchronousRequest NSURLConnection的方法获取数据。 [NSURLConnection sendAsynchronousRequest
在下面的方法中,如果我在completionHandler中进行数据处理,是否会阻塞主线程?换句话说,completionHandler 中执行的任何操作是在主线程上完成还是在后台线程上完成? + (
我打电话 [NSURLConnection sendAsynchronousRequest:request queue:queue
我正在尝试使用 POST 从 PHP 页面获取简单的文本响应。我有以下代码: func post(url: String, info: String) -> String { var URL:
我不想做的事情的示例: var b = 0 let URL: NSURL = NSURL(string: "[URL to php file]")! let request:NSMutableURL
我正在使用以下代码进行网络调用。我知道响应将在 mainQueue 中运行,因为我已将队列参数指定为 [NSOperationQueue mainQueue] 但我想知道实际的 sendAsynchr
我正在开发一个 iOS 应用程序,它可以将大量任务分派(dispatch)到我的串行队列。任务是从我的网络服务器下载图像,将其保存到磁盘,然后显示在 UIImageView 上。但是,[NSURLCo
我有一个创建 NSURLRequest 的方法,并使用 NSURLConnection 方法 sendAsynchronousRequest:queue:compltionHandler: 发送该请求
我正在编写一些执行 http 请求的 API 代码,并且我一直在使用 [NSUrlConnection:sendAsynchronousRequest:queue:completionHandler]
这是我的代码崩溃的部分: let bodyData = "username=" + username + "&password=" + password let URL: NSURL = NSURL(
我正在尝试使用 POST 从 PHP 页面获取简单的文本响应。我有以下代码: func post(url: String, info: String) -> String { var URL:
我正在使用 sendAsynchronousRequest:queue:completionHandler: 上传文件(我已经删除了一些旧的第三方库,以支持使用此 native 方法直接调用。我保留了
当我执行NSURLConnection.sendAsynchronousRequest时,它总是显示相同的错误: Invalid conversion from throwing function o
我的应用程序允许用户拍照并将其上传到 PHP 服务器。我使用 sendAsynchronousRequest 调用将数据(带有照片文件的表单)发送到服务器。调试时,所有这些调用在我的 iPad 2 上
每次用户打开应用程序时,我都必须加载 API 的刷新 token 。 在我的 appDelegate.m 中,每次应用程序打开时我都会调用此代码: if(success){ //if the url
对不起,我不知道这一点,但我想知道为什么我尝试建立与数据库的连接时会出现延迟。 我基本上是从数据库中提取数据以将信息显示回 UITableView,但连接建立似乎有延迟。 - (void)viewDi
如果互联网连接出现问题,我会尝试取消异步请求。 var connection: NSURLConnection! self.connection = NSURLConnection.sendAsync
我的应用程序中有几个内存泄漏(不!请参阅更新 1),它们都归结为异步 URLRequest。下面的代码给了我一个内存泄漏,似乎“数据”从未被释放(下面的代码在逻辑上没有在我的应用程序中使用,因为它是一
我用这段代码发出请求: - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{ //
.h @property (strong) NSString *reply; 我有以下方法: .m @synthesize reply; - (void)send { [NSURLConnecti
我是一名优秀的程序员,十分优秀!