2012-07-11 37 views
7

我想使用JSON數據類型將在iOS上創建的新對象發送到接收服務器,並使用POST方法。據我所知,在iOS中接收數據服務器,是所有的JSON處理都被蘋果公司簡化了iOS 5的引入。但是與GET JSON對象相反,POST的這些並沒有真正描述在任何我能找到的地方...如何在iOS5中將JSON數據對象發佈到服務器?

我走上嘗試解決這個問題看上去如下第一步:

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

但我真的不知道如何使用POST方法發送JSON對象到服務器。 有誰能幫我解決嗎?

回答

16

我的工作,這也使周圍試圖一點,這是我的代碼:

​​
+0

你能上什麼是你的代碼可能發生的闡述?我現在在自己的應用程序中使用過它,但我真的不知道它在做什麼。我理解字典並將其轉換爲JSON數據,但URLRequest和URLConnection的所有內容對我而言都是未知的。任何澄清將是偉大的! – Jonathan 2013-09-04 17:37:26

+1

NSURLRequest基本上是一個對象,用於設置Web抓取的屬性。在正常的提取中,你會自動設置最常用的默認值,但是因爲我想發送數據,所以我想使用HTTP POST方法,並且導致我想要接收JSON對象,所以我通過設置Content-Type並將HTTP頭字段接受爲JSON格式。要詳細瞭解HTTP協議,特別是HTTP頭,只需搜索它們或在這裏閱讀http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol和這裏http://en.wikipedia.org/wiki/List_of_HTTP_header_fields。 – CGee 2013-09-05 12:36:13

+0

要了解有關NSURLConnection的更多信息,我認爲最好的方法是在Apples文檔中閱讀它的類引用https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/的reference.html。總的來說,我只能鼓勵你首先看一看Apples文檔,因爲它是學習這些東西的好的(絕對是最新的)源代碼。 – CGee 2013-09-05 12:41:12

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]; 
    } 
}]; 
} 
相關問題