gpt4 book ai didi

iphone - iOS7 NSURLConnection sendAsynchronousRequest 因 POST 数据而失败

转载 作者:行者123 更新时间:2023-11-29 10:53:58 26 4
gpt4 key购买 nike

我的问题是采用 [NSURLConnection sendAsynchronousRequest...]POST 方法在 iOS7 上失败但在 iOS6 环境下成功。

其他信息:

  1. 在我的 iOS6 环境中可以像这样从服务器获取 JSON 数据。 (成功)

    {
    "status": 200,
    "data": [
    {
    "oauth_token": "BVgOa01tg6JvfuXOPoJS8wB26TpvAaDs"
    }
    ]
    }
  2. iOS7 上的相同代码会收到此错误消息。 (失败)

    error:Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (No value.)

  3. 我检查了服务器端的 PHP 代码,发现服务器可以从 iOS6 POST 数据中获取数据,但无法从 iOS7 中获取 POST 数据。 (同样的代码不同的结果,很奇怪。)

有没有人可以帮助我或给我建议?多谢。

我的代码如下(更新到 v3,成功)(感谢 Rob 的回答)

- (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];
}

下面的代码是在 iOS6 上的调试输出

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

下面的代码是 iOS7 上的调试输出

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

感谢 Rob 的大力帮助,我的问题得到了解决。根类(class)在代码下方。在 IOS6 中,当“idField.txt”字段上没有输入时,我可以获得 uid/withPwd 默认值。但在 iOS7 中,这段代码无法使用 (uid/withPwd) 获取默认值。感谢 Rob,我的问题解决了。

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);

将问题代码更新为适用于 iOS6 和 iOS7

// 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com