51

NSURLRequestオブジェクトにHTTPヘッダーを追加する方法はありますか?私は使用してそれらを追加するためにNSMutableURLRequest使用しました:

[request addValue:@"PC" forHTTPHeaderField:@"machineName"]
4

3 に答える 3

80

の HTTP ヘッダーを変更できないと思いますNSURLRequestNSURLRequest初期化していないオブジェクトを変更しようとしていると思いますか?

リクエストの を作成mutableCopyし、次の方法でヘッダー フィールドを設定できます。

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

その後、変更可能なリクエストを変数copyに戻すことができます。NSURLRequest

編集:以下に例を追加

/* 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);
于 2010-11-24T09:32:38.160 に答える
8

すでに回答されています(そしてそれらの回答に感謝します)が、より簡単な例を次に示します。

NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setValue:@"es" forHTTPHeaderField:@"Accept-Language"];
于 2015-07-01T14:08:23.677 に答える
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];
于 2012-07-12T12:31:07.397 に答える