2012-07-11 3 views
7

Desidero inviare un nuovo oggetto creato su iOS a un server ricevente con un metodo POST utilizzando il tipo di dati JSON. Da quello che so sulla ricezione dei dati dal server in iOS, è che tutta la gestione di JSON è stata semplificata da Apple con l'introduzione di iOS 5. Ma in contraddizione con GETting degli oggetti JSON, il POST di quelli non è realmente descritto dovunque io possa trovare ...Come si esegue il POST oggetto dati JSON sul server in iOS5?

I primi passi che ho preso per cercare di risolvere il problema sembrava come segue:

//build an info object and convert to json 
    NSDictionary *newDatasetInfo = [NSDictionary dictionaryWithObjectsAndKeys:name, @"name", language, @"language", nil]; 

    //convert object to data 
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:newDatasetInfo options:kNilOptions error:&error]; 

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
    [request setURL:someURLSetBefore]; 
    [request setHTTPMethod:@"POST"]; 
    // any other things to set in request? or working this way? 

    [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
    // What to do with NSURLConnection? Or how to send differently? 

Ma io davvero non so come inviare un oggetto JSON a un server utilizzando un metodo POST affatto. Qualcuno potrebbe aiutarmi?

risposta

16

ho lavorato fuori cercando un po 'in giro, ecco il mio codice:

//build an info object and convert to json 
    NSDictionary *newDatasetInfo = [NSDictionary dictionaryWithObjectsAndKeys:name, @"name", language, @"language", nil]; 

    //convert object to data 
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:newDatasetInfo options:kNilOptions error:&error]; 

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
    [request setURL:someURLSetBefore]; 
    [request setHTTPMethod:@"POST"]; 
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; 
    [request setHTTPBody:jsonData]; 

    // print json: 
    NSLog(@"JSON summary: %@", [[NSString alloc] initWithData:jsonData 
                encoding:NSUTF8StringEncoding]); 
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
    [connection start]; 
+0

potrebbe eventualmente elaborare su ciò che sta accadendo nel codice? L'ho usato nella mia app ora, ma sinceramente non ne so molto di quello che sta facendo. Capisco il dizionario e lo trasformo in dati per JSON, ma tutto ciò che con URLRequest e URLConnection è sconosciuto per me. Qualsiasi chiarimento sarebbe fantastico! – Jonathan

+1

Un NSURLRequest è fondamentalmente un oggetto per impostare le proprietà del recupero del Web. In feti normali avresti impostato automaticamente i valori di default più utilizzati, ma dato che voglio inviare i dati, voglio usare il metodo POST HTTP e perché voglio ricevere un oggetto JSON, sto dicendo al server questo impostando il tipo di contenuto e Accetta i campi dell'intestazione HTTP nel formato JSON. Per saperne di più sul protocollo HTTP e in particolare sull'intestazione HTTP, basta cercarli o leggere qui http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol e qui http://en.wikipedia.org/wiki/List_of_HTTP_header_fields. – CGee

+0

Per ulteriori informazioni su NSURLConnection, penso che il modo migliore sia quello di leggere il suo riferimento di classe nella documentazione di Apples qui https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/ Reference.html. In generale, posso solo incoraggiarti a dare un primo sguardo alla documentazione di Apples, in quanto è una fonte fantastica (e sicuramente aggiornata) per l'apprendimento di queste cose. – CGee

0
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
    [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://webstar52.com/demo/webcommunity/work.php"]]]; 
    NSString *post = [NSString stringWithFormat:@"&tag=%@&user_id=%@",@"getcontact",@"10408"]; 
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 
    NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]]; 
    [request setHTTPMethod:@"POST"];  
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"]; 
    [request setHTTPBody:postData]; 
    conn = [[NSURLConnection alloc]initWithRequest:request delegate:self]; 
1

NSString * strURL = @ "URL"; NSURL * url = [NSURL URLWithString: strUrl];

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

// For set postdata in string 
NSString *strPatientID = [NSString stringWithFormat:@"%@%@%@%@",self.txtDegit1.text,self.txtDegit2.text,self.txtDegit3.text,self.txtDegit4.text]; 
NSString *deviceToken = @""; 
postString = [NSString stringWithFormat:@"practiceid=%@&email=%@&password=%@&devicetoken=%@",strPatientID,self.txtUsername.text,self.txtPassword.text,deviceToken]; 


NSMutableData *httpDataBody = [NSMutableData data]; 
[httpDataBody appendData:[postString dataUsingEncoding:NSUTF8StringEncoding]]; 

NSString *strPostLength = [NSString stringWithFormat:@"%lu",[httpDataBody length]]; 

if ([httpDataBody length ] > 0){ 

    [request addValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"]; 
    [request setHTTPMethod:@"POST"]; 
    [request addValue:strPostLength forHTTPHeaderField:@"Content-Type"]; 
    [request setHTTPBody:httpDataBody]; 

} 

urlConnection = [[NSURLConnection alloc]initWithRequest:request delegate:self]; 
[urlConnection start]; 
2
- (IBAction)txtFetchData2:(id)sender { 
NSString *queryString = [NSString stringWithFormat:@"http://example.com/username.php?name=%@", [self.txtName text]]; 
NSMutableURLRequest *theRequest=[NSMutableURLRequest 
          requestWithURL:[NSURL URLWithString: 
              queryString] 
          cachePolicy:NSURLRequestUseProtocolCachePolicy 
          timeoutInterval:60.0]; 
NSDictionary* jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys: 
           @"Value1", @"Key1", 
           @"Value2", @"Key2", 
           nil]; 
NSError *error; 
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary 
         options:NSJSONWritingPrettyPrinted error:&error]; 
[theRequest setHTTPMethod:@"POST"]; 
[theRequest addValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
// should check for and handle errors here but we aren't 
[theRequest setHTTPBody:jsonData]; 
[NSURLConnection sendAsynchronousRequest:theRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { 
    if (error) { 
     //do something with error 
    } else { 
     NSString *responseText = [[NSString alloc] initWithData:data encoding: NSASCIIStringEncoding]; 
     NSLog(@"Response: %@", responseText); 

     NSString *newLineStr = @"\n"; 
     responseText = [responseText stringByReplacingOccurrencesOfString:@"<br />" withString:newLineStr];    
     [self.lblData setText:responseText]; 
    } 
}]; 
} 
Problemi correlati