异步POST请求解析JSON
一、创建URL
NSURL
*url = [NSURL
URLWithString:@"http://localhost:8080/MJServer/order"];
二、创建一个请求
NSMutableURLRequest
*request = [NSMutableURLRequest
requestWithURL:url];
三、设置请求方法
request.HTTPMethod
=
@"POST";
五、设置请求体(请求參数)
//
创建一个描写叙述订单信息的JSON数据
*orderInfo =
[NSMutableDictionary
dictionary];
=
@"123”;
=
@"123";
=
@"123";
*bodyData= [NSJSONSerialization
dataWithJSONObject:orderInfo
options:NSJSONWritingPrettyPrinted
error:nil];
request.HTTPBody
= bodyData;
六、设置请求头:这次请求体的数据不再是普通的參数。而是一个JSON数据
[request
setValue:@"application/json"
forHTTPHeaderField:@"Content-Type"];
七、发送请求
[NSURLConnection
sendAsynchronousRequest:request
queue:[NSOperationQueue
mainQueue]
completionHandler:^(NSURLResponse
*response,
NSData *data,
NSError *connectionError) {
if
(data ==
nil || connectionError)
return;
NSDictionary
*dict = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableLeaves
error:nil];
NSString
*error = dict[@"error"];
if
(error) {
[MBProgressHUD
showError:error];
}
else {
NSString
*success = dict[@"success"];
[MBProgressHUD
showSuccess:success];
}
}];
JSONObjectWithData:data
options:NSJSONReadingMutableLeaves
error:nil];
[request setValue:@"application/json"
forHTTPHeaderField:@"Content-Type"];