如何使用post方法将字典参数传递给url

时间:2016-02-22 10:38:39

标签: ios objective-c

我很累这样做..但我无法安息......

 NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"access_name", @"about us", nil];
    NSDictionary *finalDict = [[NSDictionary alloc] initWithObjectsAndKeys:dict, @"cmscontent", nil];

    NSString * post =[NSString stringWithFormat:@"%@",finalDict];

    NSData *postdata= [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength=[NSString stringWithFormat:@"%lu",(unsigned long)[postdata length]];
    NSMutableURLRequest *request= [[NSMutableURLRequest alloc]init];


    NSString *str=@"http://my url...";
    [request setURL:[NSURL URLWithString:str]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postdata];
    NSError *error;
    NSURLResponse *response;

    NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSString *returnstring=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
    NSMutableDictionary *dict12=[returnstring JSONValue];

    NSLog(@"%@",dict12);

和我的json字典参数是..

{
  "cmscontent": 
    {
          "access_name": "about us"
    }
}

所以请告诉我怎样才能得到回应? 提前谢谢。

1 个答案:

答案 0 :(得分:1)

更改forHTTPHeaderField内容类型值

[request setValue:@“application / json”forHTTPHeaderField:@“Content-Type”];

我希望这会解决.. 感谢