我想用URL POST方法在数组参数内传递数组

时间:2016-04-20 06:12:45

标签: ios iphone json

我是json的新手,我想将NSArray内的NSDictionary作为参数与url一起传递给服务器,方法是post时如何完成?我曾尝试过示例代码但未找到我的确切解决方案。下面是我的示例代码

     NSDictionary *dict = [[NSDictionary alloc]   initWithObjectsAndKeys:@"contact_name", @"kumar",@"designantion",@"sales", nil];
    NSDictionary *finalDict = [[NSDictionary alloc] initWithObjectsAndKeys:dict, @"OfficeContactPerson", nil];



    NSString *post =[[NSString alloc]initWithFormat:@"name=%@&short_name=%@&shop_no=%@&door_no=%@&floor=%@&building=%@&street=%@&area=%@&main=%@&city=%@&state=%@&district=%@&pincode=%@&telephone=%@&contact_name=%@&designatio=%@&mobile=%@&email=%@&OfficeContactPerson=%@",self.txtshowroom.text,self.txtshortname.text,self.txtshop.text,self.txtdoor.text,self.txtfloor.text,self.txtbuilding.text,self.txtstreet.text,self.txtarea.text,self.txtmain.text,cityineger,stateintegervalue,districtintegervalue,self.txtpincode.text,self.txttel.text,self.txtname.text,self.txtdesign.text,self.txtmbl.text,self.txtemail.text,finalDict];

    NSLog(@"postdata :%@",post);


    NSURL *url=[NSURL URLWithString:@"http://139.59.252.34:1337/office"];
    NSData *postData=[post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    NSString *postlength=[NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
    NSMutableURLRequest *request= [[NSMutableURLRequest alloc]init];

    [request setURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:postlength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];

    NSError *error=[[NSError alloc]init];
    NSHTTPURLResponse *response=nil;
    NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];


if (!urlData){


    UIAlertView *alert =[[UIAlertView alloc]initWithTitle:@"Error"message:FS_ERROR_LOCALIZED_DESCRIPTION(error.code)
                                                   delegate:nil
                                          cancelButtonTitle:@"OK" 
                                          otherButtonTitles:nil];
    [alert show];

}
else
{
    NSString *responseData=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
    NSLog(@"Response data ----->%@",responseData);
    NSError *error=nil;
    NSDictionary *jsonData=[NSJSONSerialization JSONObjectWithData:urlData options:NSJSONReadingMutableContainers error:&error];

);
}



 OfficeContactPerson": [
  {
    "office": 29,
    "contact_name": "Priya",
    "designation": "Prop",
    "department": "ALL",
    "mobile": "1231231231",
    "email": "priya@yopmail.com",
    "incharge_status": null,
    "created_by": null,
    "modified_by": null,
    "id": 14,
    "createdAt": "2016-04-19T13:43:59.000Z",
    "updatedAt": "2016-04-19T14:25:36.000Z"
  }
]

3 个答案:

答案 0 :(得分:1)

将数组转换为Works fine for me : - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if (([string rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]].location != NSNotFound) && !(range.length==1 && string.length==0)) { return NO; } return YES; } 字符串或制作发布数据字典,而不是将其转换为json字符串并将字符串发布到服务器。我希望下面的代码对你有用。这段代码对我来说很好 -

json

答案 1 :(得分:0)

我是ios app开发的新手,但我尝试解决。我们假设这些是你的字符串。试试这段代码:

    NSString *messages-getModuleMessages=@"messages-getModuleMessages";
NSString * authtincateToken=@"WWc3ZFZCcEtWcGxLTk1hZHhEb2hMelFNZzdGcXgwdTBxeU51NWFwUE44TnkrcnF5SCtSMDxxxxxxx";
NSString *accessSecretkey =@"WWc3ZFZCcEtWcGxLTk1hZHhEb2hMelFNZzdGcXgwdTBxeU51NWFwUE44TnkrcnF5SCtxxxxxxxx";
NSString *inboxvalue =@"hai thios is textmessage";

// this is your dictionary value are you passed
NSDictionary * callDict = [NSDictionary dictionaryWithObjectsAndKeys:messages-getModuleMessages,@"call",authtincateToken,@"authToken", accessSecretkey, @"accessSecret",inboxvalue,@"calotype",@"json",@"format",nil];

  // convert your dictionary to NSData
  NSData *jsonData = [NSJSONSerialization dataWithJSONObject:callDict options:kNilOptions error:nil];
 // this is your service request url
  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://xxxxxxxx"]];
 // set the content as format
 [request setHTTPMethod:@"POST"];
[request setHTTPBody: jsonData];
  // this is your response type        
 [request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"];
   NSError *err;
  NSURLResponse *response;
   // send the synchronous connection
   NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
   // here add your server response NSJSONSerialization
  NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err]; 

  // if u want to check the data in console
  NSString *tmp=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
    NSLog(@"%@", tmp);

答案 2 :(得分:0)

尝试以下代码行,并将它们放在前两行代码行的位置。问题只出现在那里。

    NSDictionary *dict = [[NSDictionary alloc]   initWithObjectsAndKeys:@"contact_name", @"kumar",@"designantion",@"sales", nil];
    NSDictionary *finalDict = [[NSDictionary alloc] initWithObjectsAndKeys:[NSArray arrayWithObject:dict], @"OfficeContactPerson", nil];
NSData *POST_Params = [NSJSONSerialization dataWithJSONObject:urlParams options:NSJSONWritingPrettyPrinted error:nil]; // Pass these post data in request

希望这对你有用!!

相关问题