【问题标题】:Restful API call using IOS with authentication使用带有身份验证的 IOS 调用 Restful API
【发布时间】:2012-10-03 08:32:47
【问题描述】:

我正在开发一个使用 prestashop API 使用 restful API 调用的应用程序。我是 IOS 的新手,我在 android 中编写了相同的方法:

    InputStream is = null;
try {

 DefaultHttpClient client = new DefaultHttpClient();  

    /* adding credentials as it is RESTful call */
    String username = "xyz";
    String password = "";
    client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),new UsernamePasswordCredentials(username, password));  
// HTTP get request       
HttpGet get = new HttpGet("http://www.example.com/api/");
HttpResponse responseGet;
responseGet = client.execute(get);
is = responseGet.getEntity().getContent();
} catch (ClientProtocolException e) {
    Log.e("HTTP Request","Client Protocol exception" );
} catch (IOException e) {
    Log.e("HTTP Request","IO exception" );
}

它在 Android 上完美运行。对于 IOS,我使用了这种编码,但我没有从服务器获取数据。

NSString *userName = @"XYZ";
NSString *password = @"";
//setting the string of the url taking from appliance IP.

NSString *urlString = @"http://www.example.com/api/";

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

[request setURL:[NSURL URLWithString:urlString]];

[request setHTTPMethod:@"GET"];

NSString *str1 = [NSString stringWithFormat:@"%@:%@",userName,password];

NSLog(@" str1 %@", str1);

[request addValue:[NSString stringWithFormat:@"Basic %@",str1] forHTTPHeaderField:@"Authorization"];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

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

请告诉我我做错了什么并提供任何解决方案。

谢谢!

【问题讨论】:

    标签: ios api rest authentication prestashop


    【解决方案1】:

    您可以通过这种方式构建 URL 字符串,它应该可以工作:-

    NSString *str1 = [NSString stringWithFormat:@"http://%@:%@@www.example.com/api",userName,password];
    

    我认为不需要使用 HTTP 标头字段

    【讨论】:

    • @ShoaibCheema 在调用我上面所说的构建的 URL 时是否有任何特定错误?
    【解决方案2】:

    使用Basic HTTP认证时,用户名和密码需要使用Base64编码。

    来自Wikipedia's Article on that subject:

    客户端

    当用户代理想要发送服务器认证时 它可以使用 Authorization 标头的凭据。

    Authorization 标头的构造如下:[6] 用户名和 密码被组合成一个字符串“用户名:密码”

    然后使用 Base64 对生成的字符串文字进行编码

    然后将授权方法和空格(即“基本”)放在前面 编码的字符串。例如,如果用户代理使用“Aladin”作为 用户名和“sesam open”作为密码,然后标题是 形成如下:

    Authorization: Basic QWxhZGluOnNlc2FtIG9wZW4=
    

    查看这个更正的代码:

    [...]
    NSString *str1 = [NSString stringWithFormat:@"%@:%@",userName,password];
    NSString *encodedString = [self stringByBase64EncodingWithString:str1];
    [request addValue:[NSString stringWithFormat:@"Basic %@",encodedString] forHTTPHeaderField:@"Authorization"];
    [...]
    
    
    - (NSString *)stringByBase64EncodingWithString:(NSString *)inString
    {
        NSData *data = [NSData dataWithBytes:[inString UTF8String] 
                                      length:[inString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
        NSUInteger length = [data length];
        NSMutableData *mutableData = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
    
        uint8_t *input = (uint8_t *)[data bytes];
        uint8_t *output = (uint8_t *)[mutableData mutableBytes];
    
        for (NSUInteger i = 0; i < length; i += 3) 
        {
            NSUInteger value = 0;
            for (NSUInteger j = i; j < (i + 3); j++) 
            {
                value <<= 8;
                if (j < length) 
                {
                    value |= (0xFF & input[j]); 
                }
            }
    
            static uint8_t const base64EncodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    
            NSUInteger idx = (i / 3) * 4;
            output[idx + 0] = base64EncodingTable[(value >> 18) & 0x3F];
            output[idx + 1] = base64EncodingTable[(value >> 12) & 0x3F];
            output[idx + 2] = (i + 1) < length ? base64EncodingTable[(value >> 6)  & 0x3F] : '=';
            output[idx + 3] = (i + 2) < length ? base64EncodingTable[(value >> 0)  & 0x3F] : '=';
        }
        return [[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding];
    }
    

    【讨论】:

      【解决方案3】:
          -(void)getApiCall:(NSString *)urlString response:(NSMutableArray *)response{
      
          NSString *url= urlString;
      
          NSURL * serviceUrl = [NSURL URLWithString:url];
      
          NSMutableURLRequest * serviceRequest = [NSMutableURLRequest requestWithURL:serviceUrl cachePolicy:nil timeoutInterval:10.0];
      
          [serviceRequest setValue:@"Application/json" forHTTPHeaderField:@"Content-type"];
      
          [serviceRequest setHTTPMethod:@"GET"];
      
          NSURLResponse *serviceResponse;
      
          NSError *serviceError;
      
          NSData *responseData = [NSURLConnection sendSynchronousRequest:serviceRequest returningResponse:&serviceResponse error:&serviceError];
      
          NSLog(@"REQUEST  ==== >>>>  %@",serviceUrl);
      
          NSLog(@"RESPONSE ==== >>>>  %@",responseData);
          if (responseData != nil){
              [self parseGetData:responseData responseArray:response];
          }
          else{
      
          }
      }
      
      
      -(void)parseGetData:(NSData *)response responseArray:(NSMutableArray *)responseArray
      {
          id jsonObject = Nil;
          NSString *charlieSendString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
          NSLog(@"ResponseString ==== >>>> %@",charlieSendString);
      
          if (response==nil) {
      
              NSLog(@"ERROR IN GET API....!!!!");
      
          }else{
      
              NSError *error = nil;
              jsonObject =[NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:&error];
      
      
              if (error)
              {
                  NSLog(@"%@",error);
              }
              else
              {
                  NSError *error = Nil;
                  jsonObject =[NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:&error];
      
                  if ([jsonObject isKindOfClass:[NSArray class]]) {
                      NSLog(@"Probably An Array");
                  }
                  else
                  {
                      NSLog(@"Probably A Dictionary");
                      NSDictionary *jsonDictionary=(NSDictionary *)jsonObject;
                      NSLog(@"jsonDictionary %@",[jsonDictionary description]);
                      if (jsonDictionary) {
                          [responseArray addObject:jsonDictionary];
                      }
                  }
      
              }
      
          }
      
      }
      

      【讨论】:

      • 欢迎来到 Stack Overflow!这是一段相当长的代码,因此如果您在此处添加一些描述它的作用以及它如何解决问题的文本将会很有帮助。
      猜你喜欢
      • 1970-01-01
      • 2020-08-18
      • 2011-11-28
      • 1970-01-01
      • 2014-02-09
      • 2018-06-30
      • 2013-08-21
      • 2020-01-26
      • 1970-01-01
      相关资源
      最近更新 更多