Objective j将json数据请求发送到服务器

时间:2016-06-13 09:43:39

标签: objective-c json

我正在尝试将数据发布到服务器并像这样发送数据json

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];

我已多次尝试并获得无效的数据回复

请帮助我。提前谢谢

1 个答案:

答案 0 :(得分:0)

尝试使用AFNetworking发送:

首先尝试将Json转换为Dictionary。

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

然后你可以发送这本词典:

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");
}];