2010-11-03 25 views
11

Ho un servizio WCF ospitato e sto provando a utilizzarlo all'interno di un'app per iPhone come richiesta POST JSON. Ho intenzione di utilizzare il serializzatore JSON più tardi, ma questo è quello che ho per la richiesta:Richiesta POST JSON sull'iPhone (utilizzando HTTPS)

NSString *jsonRequest = @"{\"username\":\"user\",\"password\":\"letmein\"}"; 
    NSLog(@"Request: %@", jsonRequest); 

    NSURL *url = [NSURL URLWithString:@"https://mydomain.com/Method/"]; 

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; 
    NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]]; 

    [request setHTTPMethod:@"POST"]; 
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; 
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
    [request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"]; 
    [request setHTTPBody: requestData]; 

    [NSURLConnection connectionWithRequest:[request autorelease] delegate:self]; 

Nei miei dati ricevuti Sto solo la stampa alla console:

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    NSMutableData *d = [[NSMutableData data] retain]; 
    [d appendData:data]; 

    NSString *a = [[NSString alloc] initWithData:d encoding:NSASCIIStringEncoding]; 

    NSLog(@"Data: %@", a); 
} 

E all'interno di questa risposta ottengo questo messaggio:

Data: <?xml version="1.0" encoding="utf-8"?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
    <title>Request Error</title> 
    <style> 
     <!-- I've took this out as there's lots of it and it's not relevant! --> 
    </style> 
    </head> 
    <body> 
    <div id="content"> 
     <p class="heading1">Request Error</p> 
     <p xmlns="">The server encountered an error processing the request. Please see the <a rel="help-page" href="https://mydomain.com/Method/help">service help page</a> for constructing valid requests to the service.</p> 
    </div> 
    </body> 
</html> 

Qualcuno sa perché questo accade e dove sto andando male?

che ho letto su come utilizzare ASIHTTPPost invece, ma non riesco a ottenere la demo per l'esecuzione in iOS4 :(

Grazie

EDIT:

ho appena usato per CharlesProxy ad annusare cosa sta succedendo quando chiamo da iPhone (Simulator) e questo è quello che mi ha dato: alt text

l'unica cosa strana che ho notato è che dice " SSL Proxy non abilitato per questo host: abilitare in Impostazioni proxy, percorsi SSL ". Qualcuno sa cosa significa? (Questo succede anche nel mio client Windows funzionante).

Ho appena eseguito questo sul mio client Windows e l'unica cosa che è diversa è il testo di richiesta e risposta che è crittografato. Mi manca qualcosa per usare una connessione HTTP sicura per fare questo?

NEW EDIT: Questo funziona con una richiesta non HTTPS come: http://maps.googleapis.com/maps/api/geocode/json?address=UK&sensor=true. Quindi immagino che il problema sia far sì che l'iPhone invii il POST correttamente su SSL?

Sono anche utilizzando questi metodi:

- (void) connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge 
{ 
    if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) 
    { 
     [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] 
     forAuthenticationChallenge:challenge]; 
    } 

    [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge]; 
} 

- (void) connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace 
{ 
    if([[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust]) 
    { 
     return YES; 
    } 
} 

Questo mi permette di arrivare a questo punto. Se non li uso ricevo un errore di risposta:

Il certificato per questo server non è valido. Potresti collegarti a un server che finge di essere "mydomain.com" che potrebbe mettere a rischio le tue informazioni riservate.

+0

Riesci a vedere i registri nel tuo server se hanno qualcosa di interessante in loro? – willcodejavaforfood

+0

Non ho accesso a loro in questo momento. So che il servizio è configurato e funziona con altri client. –

risposta

12

FISSO!

Modificato:

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 

a:

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

È inoltre bisogno di questi due metodi:

- (void) connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge 
{ 
    if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) 
    { 
     [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] 
     forAuthenticationChallenge:challenge]; 
    } 

    [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge]; 
} 

- (void) connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace 
{ 
    if([[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust]) 
    { 
     return YES; 
    } 
} 
+0

btw, non hai dimenticato di "restituire NO" nell'ultima riga dell'ultimo metodo? – Artem

+0

Non ne sono sicuro, io restituire SI a un metodo void.Non riesco a ricordare perché ora –

+0

@ ing0 puoi tradurre questa riga in swift plz [request setValue: @ "application/x-www-form-urlencoded" perHTTPHeaderField: @ "Content-Type"] ; –

3

Non so Objective C a tutti, ma provare a impostare l'intestazione Accept a application/json invece di application/jsonrequest.

+0

Provato prima. Dovrebbe essere così comunque? Ho fatto di nuovo e ho ancora la stessa risposta! :( –

+1

'application/json' è sicuramente il tipo MIME corretto per i dati JSON. Vedi http://stackoverflow.com/questions/477816/the-right-json-content-type – Jon

+0

OK grazie. Probabilmente sarà uno di molti errori! :) +1 –

0

cambiamento

NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]]; 

a

NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding]; 
0

DIC è NSMutable dizionario con l'oggetto e le chiavi. baseUrl è l'URL del server web server.

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic 
                 options:NSJSONWritingPrettyPrinted error:nil]; 
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 
    NSString *encodedString = [jsonString base64EncodedString]; 

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@wsName",baseUrl]]; 
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url]; 
    [theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; 
    [theRequest setHTTPMethod:@"POST"]; 
    [theRequest setValue:encodedString forHTTPHeaderField:@"Data"];