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

May*_*ari 14 iphone objective-c ios

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

x.setRequestHeader( '键', '值');

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

May*_*ari 20

您可以使用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];
Run Code Online (Sandbox Code Playgroud)