Failed To Send Json With NSUrlconnection

2019-08-23 13:59发布

问题:

i am implementing this code wich take apple in app purchase receipt from the current transaction (not listed here) i am converting it to base64 NSData object, create new NSString with the values and keys (json object) and send it trough NSUrlconnection . when the compiler hits the init with request the app crashes after 2 seconeds... without to get any response. this is the code.

    NSData *data = [NSData dataFromBase64String:receiptStr];
NSString *jsonString = [NSString stringWithFormat:@"{\"receipt-data\":\"(%@)\",\"password\":\"(%@)\"}", data, SHARED_SECRET];
NSLog(@"%@",jsonString);
savedReceipt = jsonString;
[[NSUserDefaults standardUserDefaults]setValue:savedReceipt forKey:@"savedrecipt"];
[[NSUserDefaults standardUserDefaults]synchronize];
NSData *requestdata = [jsonString dataUsingEncoding:NSUTF8StringEncoding];    //urlData = [[NSMutableData data] retain];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://sandbox.itunes.apple.com/verifyReceipt"]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[NSString stringWithFormat:@"%@",requestdata]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];

anyone have an idea what am i doing wrong? i am also new to json so it could be also a problem there.

回答1:

That's because this line in your code:

[request setHTTPBody:[NSString stringWithFormat:@"%@",requestdata]];

Is trying to setHTTPBody to some formatted NSString, when the method is actually expecting NSData.

Just use:

[request setHTTPBody: requestdata];

And see if you have better results.