如何进行json发布请求? [英] How to make json post request?
本文介绍了如何进行json发布请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须使用以下请求参数进行json发布请求
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
推荐答案
尝试一下
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发布请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文