Asynchronous POST Request Parsing JSON, asynchronous postjson
Asynchronous POST Request Parsing JSON
1. Create a URL
NSURL * url = [NSURLURLWithString: @ "http: // localhost: 8080/MJServer/order"];
2. Create a request
NSMutableURLRequest * request = [NSMutableURLRequestrequestWithURL: url];
3. Set the Request Method
Request. HTTPMethod = @ "POST ";
5. Set Request bodies (Request Parameters)
// Create a JSON data NSMutableDictionary * orderInfo = [NSMutableDictionarydictionary]; orderInfo [@ "shop_id"] = @ "123 "; orderInfo [@ "shop_name"] = @ "123"; orderInfo [@ "user_id"] = @ "123"; // convert the dictionary to data
NSData * bodyData = [NSJSONSerializationdataWithJSONObject: orderInfooptions: NSJSONWritingPrettyPrintederror: nil];
Request. HTTPBody = bodyData;
6. Set the request header: the data in the Request body is no longer a common parameter, but a JSON data
[Request setValue: @ "application/json" forHTTPHeaderField: @ "Content-Type"];
7. Send a request
[NSURLConnectionsendAsynchronousRequest: requestqueue: [NSOperationQueuemainQueue] completionHandler: ^ (NSURLResponse * response, NSData * data, NSError * connectionError ){
If (data = nil | connectionError) return;
NSDictionary * dict = [NSJSONSerializationJSONObjectWithData: dataoptions: NSJSONReadingMutableLeaveserror: nil];
NSString * error = dict [@ "error"];
If (error ){
[MBProgressHUDshowError: error];
} Else {
NSString * success = dict [@ "success"];
[MBProgressHUDshowSuccess: success];
}
}];
Note: [NSJSONSerialization dataWithJSONObject: orderInfo options: NSJSONWritingPrettyPrinted error: nil]
Convert JSON to binary data [NSJSONSerializationJSONObjectWithData: dataoptions: NSJSONReadingMutableLeaveserror: nil];
Convert binary data to JSON to set the request header: the data in the Request body is no longer a common parameter, but a JSON data
[Request setValue: @ "application/json" forHTTPHeaderField: @ "Content-Type"];