如何在iOS中将对象作为POST请求的参数发送?

时间:2015-07-01 11:13:07

标签: ios json xcode post

我需要绑定一个对象中的参数,并将该对象作为POST请求传递,以便从API接收成功的信息。

{
  customer = {
    "auth_token" = "";
    "device_id" = 3e708bf1a49cdd06;
    "email_address" = "abc@xyz.in";
    name = abc;
    number = 1234567890;
    "resend_token" = true;
   };
}

这是我需要与帖子请求一起发送的对象。但是当我将其转换为字符串并将其发布时,整个对象就成了关键,值变为nil。它将发布为{"{customer.....}=>nil}

该对象应张贴为

    {"customer:
{"auth_token":"","device_id":"3e708bf1a49cdd06","email_address":"abc@xyz.in",
"name":"abc","number":"1234567890","resend_token":"true"}}

这是我目前的尝试:

    NSArray *objects = [[NSArray alloc] initWithObjects:@"",@"3e708bf1a49cdd06",@"abc@xyz.in",@"abc",@"1234567890",@"true", nil];

    NSArray *keys = [[NSArray alloc] initWithObjects:@"auth_token",@"device_id",@"email_address",@"name",@"number",@"resend_token", nil];

    NSDictionary *tempJsonData = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];

    NSDictionary *finalJsonData = [[NSDictionary alloc] initWithObjectsAndKeys:tempJsonData,@"customer", nil];

    NSData *temp = [NSJSONSerialization dataWithJSONObject:finalJsonData options:NSJSONWritingPrettyPrinted error:nil];
    NSString *postString = [[NSString alloc] initWithData:temp encoding:NSUTF8StringEncoding];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    [request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];

    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];

    [request setHTTPMethod:@"POST"];
    NSError *error = nil; NSURLResponse *response = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

这里使用的很多代码都是在没有正确理解的情况下使用的,并直接从其他StackOverflow答案中获取,所以请原谅任何糟糕的编程习惯。

我该怎么做?任何帮助表示赞赏。谢谢。

3 个答案:

答案 0 :(得分:1)

以下是向服务器发送POST请求的示例代码。

-(void)doRequestPost:(NSString*)url andData:(NSDictionary*)data{
    requestDic = [NSDictionary dictionaryWithDictionary:data];
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:kNilOptions error:nil];
    NSString *jsonString=[[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSStringEncodingConversionAllowLossy];

    NSLog(@"Request Object:\n%@\n",data);
    NSLog(@"Request String:\n%@\n",jsonString);

    NSMutableURLRequest *theReq=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
    [theReq addValue: @"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [theReq setHTTPMethod:@"POST"];
    [theReq addValue:[NSString stringWithFormat:@"%lu",(unsigned long)[jsonString length]] forHTTPHeaderField:@"Content-Length"];
    [theReq setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];

    connection = [NSURLConnection connectionWithRequest:theReq delegate:self];
}

愿这有用,并解决您的问题。

答案 1 :(得分:1)

NSString *post =[[NSString alloc] initWithFormat:@"id=%d&restaurant_name=%@", restaurnt_Id, _rest_NameTxt.text];
    NSLog(@"PostData: %@",post);

NSURL *url=[NSURL URLWithString:EDIT_RESTAURANT_API];

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding 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:@"Accept"];
[request setValue:@"APPLICATION/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

_responseData = [[NSMutableData alloc] init];

[NSURLConnection connectionWithRequest:request delegate:self];

pragma mark - 连接方法

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [_responseData setLength:0];
    [_responseCityData setLength:0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [_responseData appendData:data];
    [_responseCityData appendData:data];
}
-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
    return YES;
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [COMMON showErrorAlert:@"Internet Connection Error!"];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {

    NSString *responseString = [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
    responseString = [responseString stringByReplacingOccurrencesOfString:@"\n" withString:@" "];
    NSLog(@"%@", responseString); 
}

在connectionDidFinishLoading方法

中完成任务

答案 2 :(得分:1)

你可以尝试下面的代码。而不是将数据转换为字符串,将其设置为HTTPBody,如

$model = Mage::getModel("module/tablemodel")->load($uuid,'uuid'); //uuid is the PK// No id field in the table
$code = $model->getCode();

echo $code;
/*Works fine as it prints the code in the table for the corresponding row, hence I'm sure the model is loaded fine*/


$data = array('status'=>1,'modified_datetime'=>date('Y-m-d H:i:s'));
$model->addData($data);
$modelApprovalLog->save();
相关问题