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

我想在Objetive C中调用返回xml数据的Web服务,我必须在头文件中传递一些信息到服务器,
就像在 javascript中,我们可以使用jquery来做,

x.setRequestHeader( ‘键’,‘值’);

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

解决方法

您可以使用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];

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...