使用IOS进行Restful API调用并进行身份验证

6

我正在开发一个应用程序,使用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);

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

谢谢!

3个回答

5
您可以按照以下方式构建URL字符串,它应该可以正常工作:-
NSString *str1 = [NSString stringWithFormat:@"http://%@:%@@www.example.com/api",userName,password];

我相信不需要使用HTTP头部字段


@ShoaibCheema,按照我上面所述的方式构建URL时是否出现了特定的错误? - ilight

4

使用基本HTTP身份验证时,用户名和密码需要使用Base64编码。

来自维基百科关于该主题的文章:

客户端

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

授权头构造如下:[6] 用户名和密码合并为一个字符串“username:password”

然后使用Base64对结果字符串进行编码。

授权方法和空格即“Basic”放在编码后面。例如,如果用户代理使用“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];
}

0
    -(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!这是一段相当长的代码,因此如果您添加一些描述它的文字以及它如何解决这里的问题,那将非常有帮助。 - josliber

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接