How to make json post request?

ε祈祈猫儿з 提交于 2019-12-12 05:17:32

问题


I have to make json post request with the following request parameters,

{   
    "method":"login", 
    "data":{  
        "username":"korea", 
        "password":"123456" 
    } 
} 

I use the following code to make the request,

NSString *jsonRequest = [NSString stringWithFormat:@"{""\"\method:\"\login\"\"\,""\data:\"{\"\"username\":\"%@\",\"password\":\"%@\"}",username,password];
    NSLog(@"Request: %@", jsonRequest);

    NSURL *url = [NSURL URLWithString:@"http://myurl..."];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];

    [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 connectionWithRequest:request delegate:self];

I have to get the response but Im not be able to get the response


回答1:


Try this

    NSDictionary *objectDic = @{@"username" : username, @"password" : password};
    NSDictionary *dataDic = @{@"data" : objectDic};
    NSDictionary *methodDic = @{@"method" : @"login", @"data": dataDic};

    NSData *requestData = [NSJSONSerialization dataWithJSONObject:methodDic
                                               options:NSJSONWritingPrettyPrinted
                                                 error:nil];
    [request setHTTPBody: requestData];


来源:https://stackoverflow.com/questions/35360298/how-to-make-json-post-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!