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
È 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"];
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];
Probabilmente dovresti aggiungere qualche spiegazione per il codice che hai postato. – MasterAM
Che cosa significa setValue: @ "application/x-www-form-urlencoded", è sth custom? –
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. –
È possibile aggiungere valore in NSMutableURLRequest
per campo_intestazione:
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setValue:VALUE forHTTPHeaderField:@"cookie"];
Questo funziona per me.
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")
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
prova questa intestazione request.addValue ("text/html", forHTTPHeaderField: "Content-Type") –
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
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;
}
}];
}
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)
- 1. Intestazioni HTTP con NSURLRequest in swift
- 2. NSURLRequest - codifica l'url per NSURLRequest POST Body (iPhone-obiettivo-C)
- 3. NSURLRequest produce risultati diversi dal client proxy HTTP
- 4. Quando scade un NSURLRequest?
- 5. richiesta con NSURLRequest
- 6. Correlare NSURLRequest con UIWebView
- 7. Simulatore iPhone - imposta proxy HTTP
- 8. Imposta richiesta HTTP "Content-Type"
- 9. NSURLConnection/NSURLRequest supporto gzip
- 10. Imposta UserAgent nella richiesta http
- 11. Creare un cookie per NSURLRequest?
- 12. NSURLRequest: Come cambiare httpMethod "GET" in "POST"
- 13. NSURLRequest ha perso l'intestazione HTTP "Autorizzazione" durante il reindirizzamento della richiesta
- 14. Come impostare un cookie con NSURLRequest?
- 15. AngularJS - imposta l'intestazione HTTP per la richiesta GET
- 16. Swift 2.0, Alamofire: imposta i cookie in HTTP Post Request
- 17. Che cos'è un aggiornamento http?
- 18. Come utilizzare NSURLRequest/NSURLConnection per scaricare un file mp3 nell'app?
- 19. symfony2 + doctrine2 @ postgresql che imposta uno schema
- 20. Wordpress plugin che imposta i dati
- 21. Come convertire NSURLRequest in NSMutableURLRequest in Swift 3?
- 22. Metodo alternativo per "setAllowsAnyHTTPSCertificate" privato di NSURLRequest: forHost: "?
- 23. iOS: è possibile aprire NSURLRequest direttamente in Safari?
- 24. Come ottenere le intestazioni HTTP
- 25. Richiesta http://mobile.twitter.com su UIWebView
- 26. Che cosa significa l'intestazione HTTP Pragma: Public?
- 27. Che cosa è esattamente un'entità HTTP?
- 28. Usa sia http che https per socket.io
- 29. Che cos'è la richiesta multipartitica http?
- 30. Unità che controlla i gestori HTTP?
Proprio quello che stavo cercando !! Thumbs Up to you !! –
C'è qualche API per aggiungere il dizionario delle intestazioni? –
Ottima risposta! Volevo sottolineare che la [risposta] di RamS (http://stackoverflow.com/a/20760445/1778488) ha una buona documentazione. – fskirschbaum