美文网首页
(05-17)网络请求--表单提交原生

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

作者: shushuzhen | 来源:发表于2019-05-17 16:33 被阅读0次

    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);
                     }
        }
    }
    

    相关文章

      网友评论

          本文标题:(05-17)网络请求--表单提交原生

          本文链接:https://www.haomeiwen.com/subject/mnpoaqtx.html