ios - 如何在 Objective-C 中设置 Http header 字段?

标签 ios objective-c iphone

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

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

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

最佳答案

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

看下面的代码,


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

关于ios - 如何在 Objective-C 中设置 Http header 字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5116192/

相关文章:

objective-c - 如何在 Objective-C 中从字符串实例化类的对象?

iphone - 如何在iPad的AppStore中隐藏iPhone App

java - 通过 smtp 发送到 iPhone 的电子邮件附件在 iPhone native 电子邮件应用程序中不可见

ios - "(NSSet *)touches"中 "event.allTouches"和 "touchesBegan:withEvent:"之间的区别

ios - 如何在方法中使用 __weak 来防止 iOS 中的内存泄漏

ios - Objective-C 协议(protocol)

iphone - UIButton 不会变灰

ios - 如何在 iOS 上的 Metal 中使用 OpenCV 函数?

ios - GoogleTagManager 错误 : _avn has no backing implementation

android - 对于 DOM 解析器来说,多大的 xml 文件应该被认为太大?