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

时间:2016-02-22 05:35:02

标签: ios objective-c

你好朋友我用post方法传递JSON参数我很厌倦这个代码..

NSDictionary *parameters = @{@"cmscontent" : @{
                                         @"access_name"   : @"about u",
                                         }
                                 };


    NSData *data = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://.........."]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"];

    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLSessionUploadTask *dataTask = [session uploadTaskWithRequest: request
                                                             fromData: data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)

                                        {
                                            NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
                                            NSLog(@"%@", json);
                                        }];

    [dataTask resume];

和我的json字典参数是..

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

所以请告诉我如何传递这类参数??

2 个答案:

答案 0 :(得分:1)

<强>先决条件

  1. 确保您的API方法在后端POST
  2. 确保您的API方法接受JSON数据。
  3. 确保所有参数名称与API方法完全相同。
  4. 使用以下方法将数据发布到API

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:@"http://....."];
    
    NSDictionary *params= @{@"cmscontent" :
                                        @{
                                            @"access_name"   : @"about u"
                                         }
                                 };
     NSError *err = nil;
     NSData *requestData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:&err];
    
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[requestData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:requestData];
    
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                               if([data length] > 0)
                               {
                                   NSError *err = nil;
                                   NSDictionary *dictResponse = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&err];
                                   NSLog(@"[%@]", dictResponse);                                  
                               }
                               else{
                                   NSLog(@"Failed To Get Response for : %@",params);
                               }
                           }];
    

答案 1 :(得分:-1)

我不确定将NSDictionary对象转换为NSString对象,然后将此字符串对象作为参数发布,就像其他字符串参数一样。我希望这会对你有帮助......

NSString *postDictionaryAsSting = [[NSString alloc]initWithData:[NSJSONSerialization dataWithJSONObject:dictObj options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
             cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];


NSData *requestData = [postDictionaryAsSting dataUsingEncoding:NSUTF8StringEncoding];

[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];

NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
 receivedData = [[NSMutableData data] retain];
}