异步POST请求解析JSON
json
1、建立URLapp
NSURL
*url = [
NSURL
URLWithString
:
@"http://localhost:8080/MJServer/order"
];
2、建立一个
请求
NSMutableURLRequest
*request = [
NSMutableURLRequest
requestWithURL
:url];
3、设置
请求方法
request.
HTTPMethod
=
@"POST"
;
5、
设置请求体(请求參数)
//
建立一个描写叙述订单信息的
JSON
数据
NSMutableDictionary
*
orderInfo
= [
NSMutableDictionary
dictionary
];
orderInfo
[
@"shop_id"
] =
@"123
”
;
orderInfo
[
@"
shop_name
"
] =
@"123"
;
orderInfo
[
@"
user_id
"
] =
@"123"
;
// 将字典转化成data
NSData
*bodyData= [
NSJSONSerialization
dataWithJSONObject
:orderInfo
options
:
NSJSONWritingPrettyPrinted
error
:
nil
];
request.
HTTPBody
=
bodyData
;
6、
设置请求头:此次请求体的数据再也不是普通的參数。而是一个
JSON
数据
[request
setValue
:
@"application/json"
forHTTPHeaderField
:
@"Content-Type"
];
7、
发送请求
[
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];
}
}];
注意:
[NSJSONSerialization dataWithJSONObject:orderInfo options:NSJSONWritingPrettyPrinted error:nil]
将JSON转化成二进制数据
[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
将二进制数据转成JSON
设置请求头:此次请求体的数据再也不是普通的參数,而是一个JSON数据
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];