我正在iOS中调用Web服务。为此,我需要在NSMutableURLRequest对象中设置标题。我的服务使用两个字符串参数,并以JSON格式返回数据。
我需要使用GET在标头中设置的字段是什么(在同时使用POSTsetValue:forHTTPHeaderField:时)。

我们不需要在使用setHTTPBody:的同时使用GET

最佳答案

我有同样的问题,我解决了(使用Iducool和Ankit Mehta的一些代码),就像这样...

NSURL *theURL = [NSURL URLWithString:@"yourURL"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL      cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0f];

//Specify method of request(Get or Post)
[theRequest setHTTPMethod:@"GET"];

//Pass some default parameter(like content-type etc.)
[theRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[theRequest setValue:@"application/json; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];

//Now pass your own parameter

[theRequest setValue:yourValue forHTTPHeaderField:theNameOfThePropertyValue];

NSURLResponse *theResponse = NULL;
NSError *theError = NULL;
NSData *theResponseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];

//Now you can create a NSDictionary with NSJSONSerialization
NSDictionary *dataDictionaryResponse = [NSJSONSerialization JSONObjectWithData:theResponseData options:0 error:&theError];
NSLog(@"url to send request= %@",theURL);
NSLog(@"%@",dataDictionaryResponse);

09-25 23:57