ios 如何在 Objective-C 中设置 Http 头字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5116192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set Http header Fields in Objective-C?
提问by Mayur Birari
I want to call web service in Objetive C which returning xml data and I have to pass some information in header to the server, just like in javascript we can do it using jquery,
我想在 Objetive C 中调用 web 服务,它返回 xml 数据,我必须将头中的一些信息传递给服务器,就像在 javascript 中我们可以使用 jquery 来完成,
x.setRequestHeader('key','value');
x.setRequestHeader('key','value');
where x is the xmlHttpRequest Object. How we can pass the header data in NSConnection class, I used google but havent find out good solution. please help me.
其中 x 是 xmlHttpRequest 对象。我们如何在 NSConnection 类中传递标头数据,我使用了谷歌但还没有找到好的解决方案。请帮我。
回答by Mayur Birari
You can pass the information in header using NSMutableURLRequest class and then call the NSURLConnection class(it will call the connection delegate).
您可以使用 NSMutableURLRequest 类传递标头中的信息,然后调用 NSURLConnection 类(它将调用连接委托)。
see the following code,
看下面的代码,
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];