2016-06-20 38 views
0

我有一個包含URL的NSString。我想用URL進行GET請求,並檢查響應爲200如何執行GET請求並檢查響應

隨着當前的代碼,我得到的響應爲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]; 
+0

你是什麼意思「響應爲零」?數據是否爲零? 'req'的價值是什麼? 「響應200」,你的意思是HTTP代碼?錯誤是否爲零? – Larme

+0

數據不是零。它包含編碼的網址。 代碼中的NSURLSession部分顯示錯誤-1001(請求超時) – Amon

+0

將URL粘貼到瀏覽器中,然後按回車鍵。怎麼了?對於GET請求 - 這是默認的 - 你可以省略data,len,甚至req(使用dataTaskWithURL)。 – vadian

回答

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];

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;所以聲明它在你的類,你用這個。

0

這可能是由於應用傳輸安全阻止了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)作爲測試。