ios NSURLRequest 设置 HTTP 标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4809047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:40:20  来源:igfitidea点击:

NSURLRequest setting the HTTP header

iphoneobjective-ccocoacocoa-touchios

提问by Raphael

I need to set the HTTP header for a request. In the documentation for the NSURLRequest class I didn't find anything regarding the HTTP header. How can I set the HTTP header to contain custom data?

我需要为请求设置 HTTP 标头。在 NSURLRequest 类的文档中,我没有找到任何关于 HTTP 标头的信息。如何设置 HTTP 标头以包含自定义数据?

回答by Larry Hipp

You need to use a NSMutableURLRequest

您需要使用NSMutableURLRequest

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

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

or to add a header:

或添加标题:

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

回答by Beslan Tularov

for 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")

回答by Ram S

 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];

回答by Umair Khalid

I know its late but may help others , For SWIFT 3.0

我知道它晚了,但可能会帮助其他人,对于 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)

回答by Saroj Kumar ojha

You can add value in NSMutableURLRequestfor HeaderField :

您可以NSMutableURLRequest为 HeaderField添加值:

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

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

This is working for me.

这对我有用。

回答by Binoy jose

Sample Code

示例代码

 - (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;


         }
     }];

}