如何提出jsonpost请求?
How to make json post request?
我必须使用以下请求参数进行 json post 请求,
{
"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];
我必须得到回应,但我无法得到回应
试试这个
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];
我必须使用以下请求参数进行 json post 请求,
{
"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];
我必须得到回应,但我无法得到回应
试试这个
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];