简体   繁体   中英

how to create json object and set it in a post body in ios using asi http request

NSString *loginurl =[NSString
                     stringWithFormat:@"/ajax/useraccount.aspx/methodname"]
NSURL *url = [NSURL URLWithString:loginPath];

NSString *loginPath = [NSString stringWithFormat:@"%@%@",singleton.website,loginurl];

asiRequest = [[ASIHTTPRequest requestWithURL:url] retain];
[asiRequest addRequestHeader:@"Content-Type" value:@"application/json"];
[asiRequest addRequestHeader:@"Accept" value:@"application/json"];
[asiRequest setRequestMethod:@"POST"];

NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
                     @"email", @"Email",
                     @"fname", @"FirstName", nil];
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];
NSLog(@"this is value %@",postdata);
NSMutableData *mutablePostData = [NSMutableData dataWithData:postdata];


[asiRequest setPostBody:mutablePostData];
[asiRequest setDelegate:self];
[asiRequest setTimeOutSeconds:60];
[asiRequest startAsynchronous];
[activityIndicator startAnimating];

i want create this type of object and set it in a post body {"objectRequest":{"email":"Email","fname":"FirstName"}}

i am unable to hit the method am i missing something or is there is another way to create this type of json object and set it in a post body thank you in advance

You can really just return that string as a body if you like. But you have to set the content type to "application/json" . One of these posts might help for doing that on ios?

How to set content-type when using initWithContentsOfUrl

JSON file set content type to application/json AFNetworking

setting content-type overwriting httpbody?

Everything looks ok with your code except you forgot to call buildPostBody method. After you set all body data you have to call this method.

[asiRequest buildPostBody];
[asiRequest startAsynchronous];

If this is a new project, I highly recommend to use any other up-to-date libraries. developers stopped developing ASIHTTPRequest long time ago.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM