JSON帖子请求不起作用

时间:2015-07-22 18:33:06

标签: objective-c iphone json xcode post

我正在使用此代码但无效。 NSLog in post和get方法为空。 我需要发布原始数据。我在Body中编写参数 - raw,它是有效的(Chrome-POSTMAN)。

这个参数:

[
    {
    "user":    "admin",
    "pass":    "admin123",
    "delete_book": 0,
    "add_book": false,
    "read_book": false,
    "bookprice": 0,
    "person": "",
    "book": 0  
    }
]

我的post方法代码:

 NSString * paramters = [[NSString alloc] initWithFormat:@"[{\"user\": \"admin\",\"pass\": \"admin123\",\"delete_book\": \"0\",\"add_book\": \"false\",\"read_book\": \"false\",\"bookprice\": \"0\",\"person\": \"\",\"book\": \"0\"}]"];
    NSError *error;

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
    NSURL *url = [NSURL URLWithString:@"http://www.xxxxxxxxx.com"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:60.0];

    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

    [request setHTTPMethod:@"POST"];

  //  NSData *postData = [NSJSONSerialization dataWithJSONObject:paramters options:0 error:&error];
  NSData *postData = [paramters dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:postData];


    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if([data length] > 0)
                {
                    NSError *err = nil;
                    NSDictionary *dictResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&err];
                    NSLog(@"Result : %@",dictResponse);
                }
                else{
                    NSLog(@"Failed To Get Response.");
                }
            });

    }];

    [postDataTask resume];

我解决了问题 这是解决方案: NSData * postData = [paramters dataUsingEncoding:NSUTF8StringEncoding];

3 个答案:

答案 0 :(得分:0)

试试这个:我想你错过了&在post字符串的开头,就在用户参数

之前
NSString  *post = [NSString stringWithFormat:@"&user=admin&pass=admin123&delete_book=0&add_book=false&read_book=false&bookprice=0&person=0&book=0"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://your-url"]]];

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

 NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

     //check here if nsdata is nil or not
      NSLog(@"nsdata is %@",data);
    //if it is nil , then there should be something wrong with the url

    NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"requestReply: %@", requestReply);

    //convert into JSON
     NSError *e = nil;
        NSData *jsonData = [requestReply dataUsingEncoding:NSUTF8StringEncoding];

        NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:jsonData options: NSJSONReadingMutableContainers error: &e];

        NSLog(@"json is %@",JSON); //check json here
}] resume];

编辑:POSTMAN参考:

enter image description here

答案 1 :(得分:0)

试试此代码...... 希望它适合你

-(void)postServerCall{
        NSString *postString = [NSString stringWithFormat:@"user=admin&pass=admin123&delete_book=0&add_book=false&read_book=false&bookprice=0&person=0&book=0"];

        NSOperationQueue *backgroundQueue = [[NSOperationQueue alloc] init];

        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://PostUrl.com"]]];

        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

        [NSURLConnection sendAsynchronousRequest:request queue:backgroundQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){

            if (error)
            {
                NSLog(@"%@",[error localizedDescription]);
            }
            else
            {
                NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                NSLog(@"result....%@",result);
            }
        }];
        }

答案 2 :(得分:0)

+ (void)callPOSTAPIWithParams:(NSDictionary *)params andCompletionHandler:(void(^)(NSDictionary *result))completionHandler
{
    NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:@"%@",<Your HOST API URL>]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];

    NSURLSession *session = [NSURLSession sharedSession];

    NSError *err = nil;
    NSData *requestData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:&err];
    //    NSLog(@"%@",[[NSString alloc] initWithData:requestData encoding:NSUTF8StringEncoding]);
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //    [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];

    NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                            completionHandler:
                                  ^(NSData *data, NSURLResponse *response, NSError *error)
                                  {
                                      dispatch_async(dispatch_get_main_queue(), ^{
                                          if([data length] > 0)
                                          {
                                              NSError *err = nil;
                                              NSDictionary *dictResponse = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&err];
                                              NSLog(@"Result : %@",dictResponse);
                                          }
                                          else{
                                              NSLog(@"Failed To Get Response.");
                                          }
                                      });
                                  }];

    [task resume];
}

<强> How to use

NSDictionary *paramters = @{@"param1":@"value1"};
[Global callPOSTAPIUsingSessionWithParams:paramters andCompletionHandler:^(NSDictionary *result) {
NSLog(@"check result");
}];