2016-02-12 89 views
-1

我必须做出具有下列请求参数JSON POST请求,如何制作json发布请求?

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

我用下面的代码发出请求,

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

我必须得到响应,但我不是能获得响应

+0

具有u本HT检查tp://stackoverflow.com/a/15749527/5362916 –

+0

参考http://stackoverflow.com/questions/15516823/create-a-json-string-in-objective-c – Signare

+0

是啊我已经试过这些例子,但问题持续存在 –

回答

2

试试这个

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