Frage

I'm trying to send JSON in a POST, but I get an error: JSON text did not start with array or object and option to allow fragments not set.

If I send this data through Postman (a browser application for testing requests) - it works fine (return data)

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;
War es hilfreich?

Lösung 4

This code works right:

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;

Andere Tipps

It looks like your JSON string is invalid. Between \"msisdn\" and \"+380503424248\" should be a :

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

You might want to examine the jsonData you are receiving in response, and make sure its actually JSON. So, as Ashutosh suggests, you should examine the NSError from sendSynchronousRequest. Also, if the JSON parsing fails, examine the NSData object:

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

With something like that, you'll be able to diagnose precisely what's going on.


As VaaChar observed (+1), your JSON request of your original question is not valid (though you've subsequently fixed it). The above code would have helped you identify that error, as you would have seen precisely what the server had responded.

Rather than building your JSON manually, which is susceptible to such simple errors, you can use NSJSONSerialization to build it for you, ensuring you have valid JSON. Thus:

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

Just try to change your params string and URLRequestto this:

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];
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top