【问题标题】:NSURLRequest setting the HTTP headerNSURLRequest 设置 HTTP 标头
【发布时间】:2011-06-16 02:15:48
【问题描述】:

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

【问题讨论】:

    标签: iphone objective-c cocoa cocoa-touch ios


    【解决方案1】:

    您需要使用NSMutableURLRequest

    NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] initWithURL:url]
                                    autorelease];
    
    [request setValue:VALUE forHTTPHeaderField:@"Field You Want To Set"];
    

    或添加标题:

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

    【讨论】:

    • 是否有任何 API 用于添加标题字典?
    【解决方案2】:
     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];
    

    【讨论】:

    • 您可能应该为您发布的代码添加一些解释。
    • setValue:@"application/x-www-form-urlencoded" 是什么意思,是自定义的吗?
    • 在 HTTP 客户端软件对 POST 的支持有限且无法在 HTTP 消息体中提交纯数据的情况下,RESTfm 能够处理在 application/x-www-form- 中编码的数据urlencoded 或 multipart/form-data 格式。注意:application/x-www-form-urlencoded 和 multipart/form-data 格式仅适用于 HTTP POST 方法 注意 2:此格式使用与 GET 查询字符串参数所需的相同的“URL 编码”方案,如此处所述.优点 支持比使用 GET 查询字符串更大的数据大小。
    【解决方案3】:

    您可以在 NSMutableURLRequest 中为 HeaderField 添加值:

    NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
    
    [request setValue:VALUE forHTTPHeaderField:@"cookie"];
    

    这对我有用。

    【讨论】:

      【解决方案4】:

      斯威夫特

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

      【讨论】:

      • 我正在使用类似的代码来发出请求,但它返回的是 nil 数据。我试图找出问题所在,我唯一能想到的是返回的响应值对于“Content-Type”具有不同的值,而不是我试图在代码开头附加的值。 request.setValue("Some value", forHTTPHeaderField: "Content-Type") 这对你有用吗?
      • 试试这个头 request.addValue("text/html", forHTTPHeaderField: "Content-Type")
      • 我也试过了,但是没用。最后使用 myParameters.dataUsingEncoding 对我有用,我正在使用其他东西,这就是我认为它不起作用的原因。感谢您的帮助。
      【解决方案5】:

      示例代码

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

      【讨论】:

        【解决方案6】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-09-19
          • 1970-01-01
          • 2012-05-15
          • 1970-01-01
          相关资源
          最近更新 更多