(05-17)网络请求--表单提交原生

2019-05-17  本文已影响0人  shushuzhen

URLStr是请求的URL,Params是参数。

- (void)formRequestWithUrlStr:(NSString *)urlStr withDicParams:(NSDictionary *)params callback:(void(^)(BOOL success))callback{
     NSURL *urlTest = [NSURL URLWithString:urlStr];
     NSMutableString *bodyContent = [NSMutableString string];
     for(NSString *key in params.allKeys){
             id value = [params objectForKey:key];
             [bodyContent appendFormat:@"--%@\r\n",@"postBound"];
             [bodyContent appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
             [bodyContent appendFormat:@"%@\r\n",value];
         }
     [bodyContent appendFormat:@"--%@--\r\n",@"postBound"];
     NSData *bodyData=[bodyContent dataUsingEncoding:NSUTF8StringEncoding];
     NSMutableURLRequest *request  = [NSMutableURLRequest requestWithURL:urlTest cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
     [request addValue:[NSString stringWithFormat:@"multipart/form-data;boundary=%@",@"postBound"] forHTTPHeaderField:@"Content-Type"];
     [request addValue: [NSString stringWithFormat:@"%zd",bodyData.length] forHTTPHeaderField:@"Content-Length"];
     [request setHTTPMethod:@"POST"];
     [request setHTTPBody:bodyData];
     NSLog(@"请求的长度%@",[NSString stringWithFormat:@"%zd",bodyData.length]);
     __autoreleasing NSError *error=nil;
     __autoreleasing NSURLResponse *response=nil;
     NSLog(@"输出Bdoy中的内容>>\n%@",[[NSString alloc]initWithData:bodyData encoding:NSUTF8StringEncoding]);
     NSData *reciveData= [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
     if(error){
             NSLog(@"出现异常%@",error);
         }else{
             NSHTTPURLResponse *httpResponse=(NSHTTPURLResponse *)response;
             if(httpResponse.statusCode==200){
                 NSLog(@"服务器成功响应!>>%@",[[NSString alloc]initWithData:reciveData encoding:NSUTF8StringEncoding]);
                 callback(1);
             }else{
                    NSLog(@"服务器返回失败>>%@",[[NSString alloc]initWithData:reciveData encoding:NSUTF8StringEncoding]);
                    callback(0);
                 }
    }
}
上一篇下一篇

猜你喜欢

热点阅读