2016-02-12 107 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];