Domanda

Come potrei fare per replicare questo in Objective-C

curl -u rick@email.com:mypassword http://foo.lighthouseapp.com/projects.xml

Ho giocato in giro con la libreria ASIHTTPRequest, ma non riesco a capirlo,

Ovviamente l'invio la mia richiesta in questo modo restituisce un errore di autenticazione:

-(void)submit:(id)sender {
    NSURL *url = [NSURL URLWithString:@"http://ldn.lighthouseapp.com/projects/63254-londonist-20/tickets.xml"];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request startSynchronous];
    NSError *error = [request error];
    if (!error) {
        NSString *response = [request responseString];
        NSLog(@"response:%@",response);
    } else {
        NSLog(@"error:%@",error);
    }
}

Questa è probabilmente molto semplice sto solo perdendo qualcosa abbastanza importante

È stato utile?

Soluzione

Da ASIHTTPRequest Documentation

con una richiesta di intestazione

[request addRequestHeader:@"Authorization"
                    value:[NSString stringWithFormat:@"Basic %@",
                           [ASIHTTPRequest base64forData:
                            [[NSString stringWithFormat:@"%@:%@", theUsername, thePassword]
                             dataUsingEncoding:NSUTF8StringEncoding]]]];

Altri suggerimenti

Se non si desidera utilizzare i framework (come me) che si può fare nel modo seguente:

NSURL *url = [NSURL URLWithString: @"https://api.github.com"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

[request setHTTPMethod:@"GET"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

NSString *authStr = [NSString stringWithFormat:@"%@:%@", login, password];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedStringWithOptions:0]];
[request setValue:authValue forHTTPHeaderField:@"Authorization"];

NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithRequest:request
         completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
             if (!error) {
              NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
              NSLog(@"%@",responseDictionary);
          }
         }] resume];

Se si utilizza ASIHTTPRequest, questo è tutto ciò che è necessario:

 request.shouldPresentCredentialsBeforeChallenge = YES;
 [request addBasicAuthenticationHeaderWithUsername:@"USER" andPassword:@"PASSWORD"];
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top