2011-01-26 11 views
81

Ho bisogno di impostare l'intestazione HTTP per una richiesta. Nella documentazione per la classe NSURLRequest non ho trovato nulla riguardo l'intestazione HTTP. Come posso impostare l'intestazione HTTP per contenere dati personalizzati?NSURLRequest che imposta l'intestazione HTTP

risposta

169

È necessario utilizzare un NSMutableURLRequest

NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] initWithURL:url] 
           autorelease]; 

[request setValue:VALUE forHTTPHeaderField:@"Field You Want To Set"]; 

o per aggiungere un'intestazione:

[request addValue:VALUE forHTTPHeaderField:@"Field You Want To Set"]; 
+1

Proprio quello che stavo cercando !! Thumbs Up to you !! –

+1

C'è qualche API per aggiungere il dizionario delle intestazioni? –

+1

Ottima risposta! Volevo sottolineare che la [risposta] di RamS (http://stackoverflow.com/a/20760445/1778488) ha una buona documentazione. – fskirschbaum

6
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60]; 

[request setHTTPMethod:@"POST"]; 
[request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
[request setValue:@"your value" forHTTPHeaderField:@"for key"];//change this according to your need. 
[request setHTTPBody:postData]; 
+2

Probabilmente dovresti aggiungere qualche spiegazione per il codice che hai postato. – MasterAM

+0

Che cosa significa setValue: @ "application/x-www-form-urlencoded", è sth custom? –

+0

In caso di supporto limitato per POST nel software client HTTP in cui non è possibile inviare dati puri nel corpo del messaggio HTTP, RESTfm è in grado di gestire i dati codificati in application/x-www-form-urlencoded o multipart/form-data formati. Nota: L'applicazione/x-www-form-urlencoded e formati multipart/form-data sono applicabili solo al POST HTTP metodo Nota 2: Questo formato utilizza lo stesso schema di 'codifica URL' come richiesto per GET stringa di query parametri come descritto qui. Vantaggi Supporto per dimensioni di dati superiori a quelle possibili utilizzando una stringa di query GET. –

0

È possibile aggiungere valore in NSMutableURLRequest per campo_intestazione:

NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url]; 

[request setValue:VALUE forHTTPHeaderField:@"cookie"]; 

Questo funziona per me.

10

per Swift

let url: NSURL = NSURL(string: APIBaseURL + "&login=1951&pass=1234")! 
var params = ["login":"1951", "pass":"1234"] 
request = NSMutableURLRequest(URL:url) 
request.HTTPMethod = "POST" 
var err: NSError? 
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err) 
request.addValue("application/json", forHTTPHeaderField: "Content-Type") 
request.addValue("application/json", forHTTPHeaderField: "Accept") 
+0

Sto usando un tipo simile di codice per fare una richiesta, ma sta restituendo ** nil ** dati. Ho provato a cosa c'è che non andava e l'unica cosa che potevo trovare era che il valore di risposta che veniva restituito ha un valore diverso per "Content-Type" rispetto a quello che sto cercando di aggiungere all'inizio del codice. 'request.setValue (" Some value ", forHTTPHeaderField:" Content-Type ")' questo funziona per te? – Sashi

+0

prova questa intestazione request.addValue ("text/html", forHTTPHeaderField: "Content-Type") –

+0

Ho provato anche quello, ma non ha funzionato. Infine usare myParameters.dataUsingEncoding ha funzionato per me, stavo usando qualcos'altro che è la ragione per cui penso che non funzionasse. Grazie per l'aiuto. – Sashi

0

codice di esempio

- (void)reqUserBalance:(NSString*)reward_scheme_id id:(NSString*)user_id success:(void (^)(id responseObject))success failure:(void (^)(id responseObject))failure{ 

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@reward/%@/user/%@/balance",URL_SERVER,reward_scheme_id,user_id]]; 
    NSLog(@"%@",url); 
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; 

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

    [NSURLConnection sendAsynchronousRequest:request 
             queue:[NSOperationQueue mainQueue] 
          completionHandler:^(NSURLResponse *response, 
               NSData *data, NSError *connectionError) 
    { 
         options:kNilOptions error:NULL]; 

     if (data.length > 0 && connectionError == nil) 
     { 
      NSDictionary * userPoints = [NSJSONSerialization JSONObjectWithData:data 
                     options:0 
                     error:NULL]; 

      NSString * points = [[userPoints objectForKey:@"points"] stringValue]; 
      NSLog(@"%@",points); 
      [SecuritySetting sharedInstance].usearAvailablePoints = points; 


     } 
    }]; 

} 
1

So che la sua tardi, ma può aiutare gli altri, per SWIFT 3,0

let url = NSURL(string: "http://www.yourwebsite.com") 
    let mutAbleRequest = NSMutableURLRequest(URL: url!) 
    mutAbleRequest.setValue("YOUR_HEADER_VALUE", forHTTPHeaderField:"YOUR_HEADER_NAME") 
    myWebView.loadRequest(mutAbleRequest) 
Problemi correlati