我想用 URL POST 方法在字典参数中传递数组

Posted

技术标签:

【中文标题】我想用 URL POST 方法在字典参数中传递数组【英文标题】:I want to pass the array inside the dictionary parameter with URL POST method 【发布时间】:2016-04-20 06:12:45 【问题描述】:

我是 json 新手,我想将 NSDictionary 中的 NSArray 作为参数与 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"
  
]

【问题讨论】:

将数组转换为 Json 字符串并通过服务器发送该字符串值 【参考方案1】:

将数组转换为json 字符串或制作发布数据字典,而不是将其转换为json 字符串并将字符串发布到服务器。我希望下面的代码对你有用。这段代码对我来说很好用-

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

NSURL *url=[NSURL URLWithString:@"http://139.59.252.34:1337/office"];
NSData *postData=[[[NSString alloc]initWithData:[NSJSONSerialization dataWithJSONObject:finalDict options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding] 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:[NSString stringWithFormat:@"%ld",(long)(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];



【讨论】:

fficeContactPerson": [ "office": 29, "contact_name": "Priya", "designation": "Prop", "department": "ALL", "mobile": "1231231231" ,“电子邮件”:“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" ] hw cn 我通过了上述数据 这是字典还是数组? 字典内的数组 您上面的“发布”字符串不是您发布到服务器的正确 json 格式。就像在第一行代码中所做的那样,使用字典为每个数据创建一个键/值对。【参考方案2】:

我是 ios 应用程序开发的新手,但我尝试解决。让我们假设这些是你的字符串。试试这个代码:

    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);

【讨论】:

【参考方案3】:

尝试下面的代码行并将它们放在前两行代码的位置。问题只是在那里。

    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

希望这对你有用!!

【讨论】:

fficeContactPerson": [ "office": 29, "contact_name": "Priya", "designation": "Prop", "department": "ALL", "mobile": "1231231231" ,“电子邮件”:“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" ] 而且我还有一些文本字段,例如名称商店名称,例如 dat br0 officecontactpersn 是键,然后是数组 在 JSON 中 [] 表示数组, 表示字典。你按照我的回答试过了吗?

以上是关于我想用 URL POST 方法在字典参数中传递数组的主要内容,如果未能解决你的问题,请参考以下文章

request模块

使用 Alamofire 请求方法在 POST 的请求正文中发送 JSON 对象数组

AFNetworking 2.0 发送带有字典参数数组的发布请求

WKWebView POST 请求

将数组作为url参数传递并重定向到新页面

如何在调用WebService方法时,传递对象数组参数