2010-11-24 27 views

答えて

79

私はあなたがNSURLRequestのHTTPヘッダを変更することができるとは思いません。あなたが初期化していないNSURLRequestオブジェクトを修正しようとしていると思いますか?

あなたはあなたの要求のmutableCopyを作成し、以下の方法でヘッダフィールドを設定することができます:あなたが戻ってあなたのNSURLRequest変数への変更可能な要求をcopyことができた後

-(void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field. 

EDIT

/* Create request variable containing our immutable request 
* This could also be a paramter of your method */ 
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.stackoverflow.com"]]; 

// Create a mutable copy of the immutable request and add more headers 
NSMutableURLRequest *mutableRequest = [request mutableCopy]; 
[mutableRequest addValue:@"Hless" forHTTPHeaderField:@"X-user-nick"]; 

// Now set our request variable with an (immutable) copy of the altered request 
request = [mutableRequest copy]; 

// Log the output to make sure our new headers are there  
NSLog(@"%@", request.allHTTPHeaderFields); 
+1

おかげで、あなたはNSURLRequestにHttpヘッダーを追加することはできません。NSURLRequestを入手できるのは正直なところです。NSURLRequestを使用したかったのは、代理人 "didRece iveData "しかし、NSMutableURLRequestの代わりにスレッドを使用しています。 –

+0

私はこれを投稿してからしばらく時間がかかっていることを知っていますが、多少の人気のある要求のために、私は正解の答えを更新し、例を追加しました。 – Hless

+0

こんにちは@私はこの方法を試みましたが、私はまだ無許可になっています。あなたは私の質問をここで見ることができます:http://stackoverflow.com/questions/40342728/sending-httpheaderfield-for-nsurlrequest-in-afmultipartformdata –

5
NSString *urlString = @"http://10.28.79.63:3000/testing"; 

NSMutableURLRequest *imageRequest = [[NSMutableURLRequest alloc] init] ; 
[imageRequest setURL:[NSURL URLWithString:urlString]]; 
[imageRequest setHTTPMethod:@"POST"]; 

NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"]; 
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary]; 

[imageRequest setValue:contentType forHTTPHeaderField: @"content-Type"]; 
NSMutableData *body = [NSMutableData dataWithCapacity:[imageData length] + 512]; 
[body appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary]dataUsingEncoding:NSUTF8StringEncoding]]; 

//Here u adds the Headers which will be posted in body 

[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; content-type: application/octet-stream; name=\"userfile\"; filename=\"inLove.mp4\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 


[body appendData:[NSData dataWithData:imageData]]; 
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 

[imageRequest setHTTPBody:body]; 
NSURLConnection * theConnection = [[NSURLConnection alloc] initWithRequest:imageRequest 
               delegate:self]; 
7

の下に追加の例は、すでに答え(およびそれらの答えのおかげで)が、ここではもっと簡単な例です:応答のための

NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]]; 
[request setValue:@"es" forHTTPHeaderField:@"Accept-Language"]; 
+0

これは確かに最短の正解です(Y) – Adeel

関連する問題