简体   繁体   中英

Objective c post with json data request to server

I am trying to post data to server and send data json like this

data: {"userID":"AAAAA","token":"12345","type":"BBB","version":"45"}

here is image

 NSDictionary *requestDictionary = @{@"data" : @{
                                       @"{userID" : @"AAA", @"token ": @"12345",@"type":@"iOS",@"version":@"1}"}};

NSURL *urls =[NSURL URLWithString:[NSString stringWithFormat:@"http://URL/send_code"]];

self.request = [[NSMutableURLRequest alloc]init];

[self.request setURL:urls];
NSString *contentType = [NSString stringWithFormat:
                         @"application/json"];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

[request setHTTPMethod:@"POST"];
[request addValue:@"IOS" forHTTPHeaderField: @"X-Application-Platform"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

[request setHTTPBody:[NSJSONSerialization dataWithJSONObject:requestDictionary options:0 error:nil]];
NSData *postdata = [NSJSONSerialization dataWithJSONObject:requestDictionary options:0 error:nil];

urlconnection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:true];

i ve tried several times and get invalid data response

please help me.thanks in advance

Try to send using AFNetworking:

First try to convert Json into Dictionary.

NSError *error;
NSData *objectData = [@"{Your dictionary}" dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
                                      options:NSJSONReadingMutableContainers 
                                        error:&error];

Then you can send this dictionary:

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

[manager POST:@"your_URL" parameters:json progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    NSLog(@"Complete");
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    NSLog(@"Fail");
}];

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