iPhone: Http POST JSON метод - PullRequest
       6

iPhone: Http POST JSON метод

0 голосов
/ 27 февраля 2012

Мне нужно отправить некоторые данные на сервер. Я использовал следующий код:

NSString *add1=@"";
    NSString *pin=@"";
    NSString *add2=@"";
    NSString *total=tot;
    NSString *tax1=tax;
    NSString *json=[NSString stringWithFormat:@"id: %@ menuname: %@ price: %@ quantity: %@ spiceness: %@",ids,mname,mprice,mquan,mspice];
  //  NSLog(@"JSON %@",json);
    NSString *info=[NSString stringWithFormat:@"cname: %@ ad1: %@ ad2: %@ pincode: %@ pher: %@ cmailadress: %@ res_id: %d details: %@ maintotal: %@ tax: %@ pdate:%@ ptime: %@ sffers:%@ specialinstructions:%@",personName,add1,add2,pin,phno,emailid,1,json,total,tax1,pdate,ptime,offr,sinstr];

    NSLog(@"JSON %@",info);

    NSString *jsonResponse=[info JSONRepresentation];

    NSString *stringToAppend = @"?&method=sder&res_id=1&orr=";

    NSString *newURLAsString = [NSString stringWithFormat:@"%@%@%@",URL,stringToAppend,jsonResponse];

    NSURL *url = [NSURL URLWithString:newURLAsString];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];


       NSData *requestData = [NSData dataWithBytes:[jsonResponse UTF8String] length:[jsonResponse length]];

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
       [request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
       [request setHTTPBody: requestData];

    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    if (connection) {
        //       receivedData = [[NSMutableData data] retain];
    }

Я получил следующую ошибку при использовании этого:

-JSONRepresentation failed. Error trace is: (
    "Error Domain=org.brautaset.JSON.ErrorDomain Code=4 \"Not valid type for JSON\" UserInfo=0x792bd80 {NSLocalizedDescription=Not valid type for JSON}"

1 Ответ

1 голос
/ 27 февраля 2012

Вы должны использовать NSDictionary при вызове JSONRepresentation. Ваша информация NSString.

Сделай так:

NSString* jsonString = [jsonDict JSONRepresentation];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...