我在网络服务中有这个结构:
{
"user":
{
"email":"prueba@hotmail.com",
"password":"12345678",
"objectId":"2334jklwf",
"token":"12334023ijrdadfsdoifj"
}
}
我需要使用HTTP POST
(iOS 9)制作NSURLSession
。所以我需要创建一个带有名为'user'
的密钥的字典,并在该密钥内部显示所有键的字典,对吧? POST
它的方式是什么?
答案 0 :(得分:0)
以下功能对我有用,你可以尝试一下。您可以在header values
对象中设置NSURLSessionConfiguration
。
- (void)callWS {
NSURL * url = [NSURL URLWithString:@"Your URL"];
NSURLSessionConfiguration * config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession * session = [NSURLSession sessionWithConfiguration:config];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = @"POST";
NSDictionary * dicData = [NSDictionary dictionaryWithObjectsAndKeys:@"prueba@hotmail.com",@"email",@"12345678",@"password",@"2334jklwf",@"objectId", nil];
NSDictionary *dictionary = @{@"user": dicData};
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary
options:kNilOptions error:&error];
if (!error) {
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
fromData:data completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
// Handle response here
}];
[uploadTask resume];
}
}
答案 1 :(得分:-1)
您可以在请求正文中设置json
request.HTTPMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
if let data = param?.JsonStringWithPrettyPrint(){
request.HTTPBody = NSString(string: data).dataUsingEncoding(NSUTF8StringEncoding)
}
在那里:param是你的字典 和JsonStringWithPrettyPrint是NSDictionary的扩展:
extension NSDictionary {
func JsonStringWithPrettyPrint()-> String? {
do{
let data = try NSJSONSerialization.dataWithJSONObject(self, options: NSJSONWritingOptions.PrettyPrinted)
return NSString(data: data, encoding: NSUTF8StringEncoding) as? String
}catch{
return nil
}
}
}