6

prestashop API を使用して安静な 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);

私が間違っていることを教えてください。解決策があれば教えてください。

ありがとう!

4

3 に答える 3

5

この方法で URL 文字列を作成でき、動作するはずです:-

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

私が信じているHTTPヘッダーフィールドを使用する必要はありません

于 2012-10-03T08:41:36.273 に答える
3

基本 HTTP 認証を使用する場合、ユーザー名とパスワードは Base64 エンコーディングを使用してエンコードする必要があります。

その主題に関するウィキペディアの記事から:

クライアント側

ユーザー エージェントがサーバー認証資格情報を送信する場合、Authorization ヘッダーを使用できます。

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];
}
于 2012-10-03T08:59:45.837 に答える
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];
                }
            }

        }

    }

}
于 2015-09-25T03:03:38.170 に答える