Request with NSURLRequest

后端 未结 2 568
清歌不尽
清歌不尽 2020-12-30 08:33

I\'m trying do to an app which uses a database (actually in my localhost), I tried with ASIHTTPRequest but having so much troubles with iOS 5 (I learnt how to use ASIHTTPReq

相关标签:
2条回答
  • 2020-12-30 09:22

    Try the below code it is one of the simple ways to consume a web service(json)

    NSURL *url = [NSURL URLWithString:@"yourURL"];
    
    NSMutableURLRequest *urlReq=[NSMutableURLRequest requestWithURL:url];
    
    NSURLResponse *response;
    
    NSError *error = nil;
    
     NSData *receivedData = [NSURLConnection sendSynchronousRequest:urlReq
                                                  returningResponse:&response
                                                             error:&error];
    if(error!=nil)
    {
       NSLog(@"web service error:%@",error);
    }
    else
    {
     if(receivedData !=nil)
     {
        NSError *Jerror = nil;
    
        NSDictionary* json =[NSJSONSerialization
                             JSONObjectWithData:receivedData
                             options:kNilOptions
                             error:&Jerror];
    
       if(Jerror!=nil)
       {
        NSLog(@"json error:%@",Jerror);
       }
     }
    }
    

    Hope this helps.

    0 讨论(0)
  • 2020-12-30 09:35

    try this:

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL
    
                                URLWithString:@"http://localhost:8888/testNSURL/index.php"]
    
                                cachePolicy:NSURLRequestUseProtocolCachePolicy
    
                                timeoutInterval:60.0];
    
    [request setHTTPMethod:@"POST"];
    NSString *postString = @"myVariable=Hello world !";
    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
    
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    if (theConnection) {
    
        receiveData = [NSMutableData data];   
    
    }
    

    seen here https://stackoverflow.com/a/6149088/1317080

    0 讨论(0)
提交回复
热议问题