有時進行網(wǎng)絡請求是需要將參數(shù)設置到請求體的body里面,又稱將對象作為參數(shù)傳入后臺,params視情況而定?我是用的是AFNetworking,代碼如下,里面有詳細注釋
- (void)startRequestWithUrl:(NSString *)url method:(NSString *) method params:(NSDictionary *)params{
? ? NSError *error;
? ? NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
? ? NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
? ? AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
? ? //method 為時post請求還是get請求
? ? NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:method URLString:url parameters:nil error:nil];
? ? //設置超時時長
? ? request.timeoutInterval= 30;
? ? //設置上傳數(shù)據(jù)type
? ? [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
? ? //設置接受數(shù)據(jù)type
? ? [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
? ? NSString *token = @"123456789098765432";
? ? [request setValue:token forHTTPHeaderField:@"token"];
? ? //將對象設置到requestbody中 ,主要是這不操作
? ? [request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
? ? //進行網(wǎng)絡請求
? ? [[manager dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
? ? } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
? ? } completionHandler:^(NSURLResponse * _Nonnull response, id? _Nullable responseObject, NSError * _Nullable error) {
? ? ? ? if (!error) {
? ? ? ? ? ? NSLog(@"Reply JSON: %@", responseObject);
? ? ? ? } else {
? ? ? ? ? ? NSLog(@"Error: %@, %@, %@", error, response, responseObject);
? ? ? ? }
? ? }] resume];
}
參數(shù)格式如下:
? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? "xxx": "xxxxxx",
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?"xxxx": [ ? ? ??
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?"xxxx": "xxxx",
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?"xxxx": "xxxx"
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?]
? ? ? ? ? ? ? ? ? ? ? }