如何执行GET请求并检查响应

时间:2016-06-20 10:04:33

标签: ios objective-c nsurlsession

我有一个包含URL的NSString。我想使用URL发出GET请求,并检查响应是否为200.

使用当前代码,我的响应为0。

这是我的代码:

NSString *Url = @"http://www.xyx.com";     
NSData *data = [Url dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *len = [NSString stringWithFormat:@"%lu", (unsigned long)[data length]];
    NSMutableURLRequest *req = [[NSMutableURLRequest alloc]init];
    [req setURL:[NSURL URLWithString:Url]];
    [req setHTTPMethod:@"GET"];



   NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    [[session dataTaskWithRequest:req completionHandler:^(NSData data, NSURLResponse response, NSError *error) {
        NSString *req = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
        NSLog(@"Reply = %@", req);
    }]resume];

3 个答案:

答案 0 :(得分:0)

使用此代码适用于您:

-(void)yourMethodNAme
{
    NSString *post = @"";
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

    [request setURL:[NSURL URLWithString:@"Your URL"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];

    NSURLResponse *response;
    NSError *err;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

    //NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
    //NSLog(@"str : %@",str);

    NSDictionary *dict6 = [self cleanJsonToObject:responseData];
    //NSLog(@"str : %@",dict6);
}

- (id)cleanJsonToObject:(id)data
{
    NSError* error;
    if (data == (id)[NSNull null])
    {
        return [[NSObject alloc] init];
    }
    id jsonObject;
    if ([data isKindOfClass:[NSData class]])
    {
        jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    }
    else
    {
        jsonObject = data;
    }
    if ([jsonObject isKindOfClass:[NSArray class]])
    {
        NSMutableArray *array = [jsonObject mutableCopy];
        for (int i = (int)array.count-1; i >= 0; i--)
        {
            id a = array[i];
            if (a == (id)[NSNull null])
            {
                [array removeObjectAtIndex:i];
            } else
            {
                array[i] = [self cleanJsonToObject:a];
            }
        }
        return array;
    }
    else if ([jsonObject isKindOfClass:[NSDictionary class]])
    {
        NSMutableDictionary *dictionary = [jsonObject mutableCopy];
        for(NSString *key in [dictionary allKeys])
        {
            id d = dictionary[key];
            if (d == (id)[NSNull null])
            {
                dictionary[key] = @"";
            } else
            {
                dictionary[key] = [self cleanJsonToObject:d];
            }
        }
        return dictionary;
    }
    else
    {
        return jsonObject;
    }
}

最后在ViewDidLoad中将其称为[self yourMethodNAme];

答案 1 :(得分:0)

  -(void) httpGetWithCustomDelegateWithString: (NSString*)urlString
  {
[self startActivity];

[[UIApplication sharedApplication] beginIgnoringInteractionEvents];

NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];

NSURL *url = [NSURL URLWithString:urlString];

NSURLSessionDataTask *dataTask =[defaultSession dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
                                 {
                                     NSLog(@"Response:%@ %@\n", response, error);

                                     if(error == nil)
                                     {
                                         //NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
                                         //NSLog(@"Data = %@",text);


                                         id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
                                         deserializedDictionary = nil;

                                         if (jsonObject != nil && error == nil)
                                         {
                                             if ([jsonObject isKindOfClass:[NSDictionary class]])
                                             {
                                                 //Convert the NSData to NSDictionary in this final step
                                                 deserializedDictionary = (NSDictionary *)jsonObject;
                                                 NSLog(@"dictionary : %@",deserializedDictionary);
                                             }
                                             if ([jsonObject isKindOfClass:[NSArray class]])
                                             {
                                                 deserializedArr = (NSArray*)jsonObject;
                                                 NSLog(@"array : %@",deserializedArr);
                                             }
                                         }

                                         [self setAlert];
                                     }
                                     else
                                     {
                                         [activityView removeFromSuperview];
                                         [[UIApplication sharedApplication] endIgnoringInteractionEvents];
                                         [self showAlert:@"Error" :@"Network error occured." :@"Ok"];
                                     }
                                 }];

[dataTask resume];

  }

只需使用上面的代码并调用它 [self httpGetWithCustomDelegateWithString:@"webStringHere"]; 在完成时,它将调用方法-(void)setAlert;,因此在您使用此类的类中声明它。

答案 2 :(得分:0)

这可能是由于App Transport Security阻止了HTTP。

App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.

尝试向安全网站(例如https://www.google.com)发出请求作为测试。