【问题标题】:How to set Http header Fields in Objective-C?如何在 Objective-C 中设置 Http 标头字段?
【发布时间】:2011-02-25 10:37:57
【问题描述】:

我想在 Objetive C 中调用返回 xml 数据的 Web 服务,我必须将标头中的一些信息传递给服务器, 就像在 javascript 中一样,我们可以使用 jquery 来完成,

x.setRequestHeader('key','value');

其中 x 是 xmlHttpRequest 对象。 我们如何在 NSConnection 类中传递标头数据, 我用谷歌,但还没有找到好的解决方案。 请帮我。

【问题讨论】:

    标签: ios objective-c iphone


    【解决方案1】:

    您可以使用 NSMutableURLRequest 类在标头中传递信息,然后调用 NSURLConnection 类(它将调用连接委托)。

    看下面的代码,

    
    NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:[myServerUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]
                                                            cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                        timeoutInterval:60.0];
    //do post request for parameter passing 
    [theRequest setHTTPMethod:@"POST"];
    
    //set the content type to JSON
    [theRequest setValue:@"xml" forHTTPHeaderField:@"Content-Type"];
    
    //passing key as a http header request 
    [theRequest addValue:@"value1" forHTTPHeaderField:@"key1"];
    
    //passing key as a http header request
    [theRequest addValue:@"value2" forHTTPHeaderField:@"key2"];
    
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    
    if( theConnection )
    {
        webData = [[NSMutableData data] retain];
    }
    else
    {
        NSLog(@"theConnection is NULL");
    }
    
    [theConnection release];
    

    【讨论】:

    • 在 NSMutableURLRequest 中添加自定义键值对 HTTPS URL 不起作用...有什么想法吗??
    • 网址是 HTTP 还是 HTTPS 没关系。 NSMutableRequest 在任何一种情况下都发送属性。您是否处理过 HTTPS 服务的身份验证委托?
    • 您声称将内容类型设置为 JSON,但尚未将其设置为 xml?您必须将其设置为application/json
    • 嘿@MayurBirari 你也能回答这个问题吗:stackoverflow.com/questions/40342728/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-24
    • 2014-05-16
    • 2020-04-17
    • 2021-03-27
    相关资源
    最近更新 更多