2012-07-11 17 views
7

Tôi muốn gửi một đối tượng mới được tạo trên iOS đến máy chủ nhận bằng phương thức POST sử dụng loại dữ liệu JSON. Từ những gì tôi biết về việc nhận dữ liệu từ máy chủ trong iOS, là tất cả việc xử lý JSON đã được Apple đơn giản hóa bằng việc giới thiệu iOS 5. Nhưng ngược lại với việc GET các đối tượng JSON, POST không thực sự được mô tả ở bất cứ đâu tôi có thể tìm thấy ...Làm cách nào để POST đối tượng dữ liệu JSON lên máy chủ trong iOS5?

các bước đầu tiên tôi đã cố gắng và giải quyết vấn đề nhìn như sau:

//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? 

Nhưng tôi thực sự không biết làm thế nào để gửi một đối tượng JSON đến một máy chủ bằng cách sử dụng phương thức POST. Có ai vui lòng giúp tôi không?

Trả lời

16

tôi làm việc nó ra bằng cách cố gắng một chút xung quanh, đây là mã của tôi:

//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

bạn có thể có thể xây dựng trên những gì đang xảy ra trong mã của bạn? Tôi đã sử dụng nó trong ứng dụng của riêng tôi bây giờ, nhưng tôi thành thật không biết nhiều về những gì nó đang làm. Tôi hiểu từ điển và biến nó thành dữ liệu cho JSON, nhưng tất cả mọi thứ với URLRequest và URLConnection là không rõ đối với tôi. Bất kỳ làm rõ sẽ là tuyệt vời! – Jonathan

+1

NSURLRequest về cơ bản là một đối tượng để đặt thuộc tính tìm nạp trên web của bạn. Trong các lần tải bình thường, bạn sẽ có các mặc định được sử dụng nhất được đặt tự động, nhưng khi tôi muốn gửi dữ liệu tôi muốn sử dụng phương thức HTTP POST và khiến tôi muốn nhận một đối tượng JSON Tôi đang nói với máy chủ điều này bằng cách thiết lập Kiểu nội dung và Chấp nhận các trường tiêu đề HTTP thành định dạng JSON. Để tìm hiểu thêm về giao thức HTTP và đặc biệt là tiêu đề HTTP, hãy tìm kiếm chúng hoặc đọc tại đây http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol và tại đây http://en.wikipedia.org/wiki/List_of_HTTP_header_fields. – CGee

+0

Để tìm hiểu thêm về NSURLConnection Tôi nghĩ cách tốt nhất là chỉ đọc tài liệu tham khảo lớp học của nó trong Tài liệu về Táo tại đây https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/ Reference.html. Nói chung tôi chỉ có thể khuyến khích bạn đầu tiên có một cái nhìn vào tài liệu Apples đầu tiên, vì nó là một nguồn tuyệt vời (và chắc chắn up-to-date) cho việc học những điều này. – 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 = [URL NSURLVới chuỗi: 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]; 
    } 
}]; 
}