通过POST发送JSON时出错

时间:2014-05-15 13:26:54

标签: ios json post

我正在尝试在POST中发送JSON,但是我收到一个错误: JSON文本没有以数组或对象开头,并且选项允许未设置片段。

如果我通过邮递员(用于测试请求的浏览器应用程序)发送此数据 - 它工作正常(返回数据)

NSString*params = @"{  \"devID\" : \"I:73899EAB-BB4F-4AE5-A691-8505E6AF0C3A\", \"msisdn\": \"+380503424248\"}";

NSURL* url = [NSURL URLWithString:@"https://link.privatbank.ua/dms/gpsMobile/commonSMART/init?app=gpsMobile"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";

request.HTTPBody = [params dataUsingEncoding:NSUTF8StringEncoding];


NSURLResponse *response;
NSError *error;
NSData *jsonData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];

NSDictionary *results = jsonData ? [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&error] : nil;

4 个答案:

答案 0 :(得分:3)

看起来您的JSON字符串无效。 \"msisdn\"\"+380503424248\"之间应为:

NSString*params = @"{\"devID\" : \"I:73899EAB-BB4F-4AE5-A691-8505E6AF0C3A\", \"msisdn\" : \"+380503424248\"}";

答案 1 :(得分:1)

您可能想要检查您在回复时收到的jsonData,并确保其实际为JSON。所以,正如Ashutosh建议的那样,你应该从NSError检查sendSynchronousRequest。此外,如果JSON解析失败,请检查NSData对象:

NSError *requestError;
NSURLResponse *response;
NSData *jsonData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];

// examine the HTTP status code (if any)

if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
    int statusCode = [(NSHTTPURLResponse *)response statusCode];
    if (statusCode != 200) {
        NSLog(@"%s: sendSynchronousRequest responded with statusCode = %d; expected 200", __PRETTY_FUNCTION__, statusCode);
    }
}

// examine the `requestError` (if any)

if (!jsonData) {
    NSLog(@"%s: sendSynchronousRequest error = %@", __PRETTY_FUNCTION__, requestError);
}

// now try to parse the response, reporting the JSON object if successful; reporting the `NSString` representation of the `jsonData` if not

NSError *parseError;
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&parseError];
if (results) {
    NSLog(@"%s: JSON parse succeeded; results = %@", __PRETTY_FUNCTION__, results);
} else {
    NSLog(@"%s: JSON parse failed; parseError = %@"; jsonData = %@", __PRETTY_FUNCTION__, parseError, [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
}

通过类似的方式,您将能够准确诊断出正在发生的事情。


正如VaaChar所观察到的(+1),您对原始问题的JSON请求无效(尽管您后来已经修复了它)。上面的代码可以帮助您识别错误,因为您可以准确地看到服务器已经响应的内容。

您可以使用NSJSONSerialization为您构建JSON,确保您拥有有效的JSON,而不是手动构建易受此类简单错误影响的JSON。因此:

NSDictionary *params = @{@"devID"  : @"I:73899EAB-BB4F-4AE5-A691-8505E6AF0C3A",
                         @"msisdn" : @"+380503424248"};

NSError *jsonError;
NSData *body = [NSJSONSerialization dataWithJSONObject:params options:0 error:&jsonError];
if (!body) {
    NSLog(@"%s: dataWithJSONObject failed: %@", __PRETTY_FUNCTION__, jsonError);
} else {
    request.HTTPBody = body;
}

答案 2 :(得分:0)

尝试将params字符串和URLRequest更改为:

NSString *params = @"devID=73899EAB-BB4F-4AE5-A691-8505E6AF0C3A&msisdn=+380503424248";
NSData *postData = [params dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setValue:postLenght forHTTPHeaderField:@"Content-Lenght"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPShouldHandleCookies:YES];
[request setHTTPBody:postData];

答案 3 :(得分:0)

此代码可以正常使用:

NSDictionary *params = @{@"devID"  : [self getUUID],
                         @"msisdn" : [[NSUserDefaults standardUserDefaults] stringForKey:@"phone_number"]};

NSError *jsonError;
NSData *body = [NSJSONSerialization dataWithJSONObject:params options:0 error:&jsonError];

NSURL* url = [NSURL URLWithString:@"https://link.privatbank.ua/dms/gpsMobile/commonSMART/init?app=gpsMobile"];

request.URL = url;
request.HTTPMethod = @"POST";
[request setValue:@"application/json" forHTTPHeaderField:@"Content-type"];  
request.HTTPBody = body;

NSURLResponse *response;
NSError *error;
NSData *jsonData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];

NSDictionary *results = jsonData ? [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&error] : nil;