요청에 대한 HTTP 헤더를 설정해야합니다. NSURLRequest 클래스에 대한 문서에서 HTTP 헤더에 관한 내용을 찾지 못했습니다. 사용자 지정 데이터를 포함하도록 HTTP 헤더를 설정하려면 어떻게해야합니까?
답변:
NSMutableURLRequest 를 사용해야합니다.
NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] initWithURL:url]
autorelease];
[request setValue:VALUE forHTTPHeaderField:@"Field You Want To Set"];
또는 헤더를 추가하려면 :
[request addValue:VALUE forHTTPHeaderField:@"Field You Want To Set"];
Swift 용
let url: NSURL = NSURL(string: APIBaseURL + "&login=1951&pass=1234")!
var params = ["login":"1951", "pass":"1234"]
request = NSMutableURLRequest(URL:url)
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("Some value", forHTTPHeaderField: "Content-Type")
이것이 당신을 위해 일하고 있습니까?
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"your value" forHTTPHeaderField:@"for key"];//change this according to your need.
[request setHTTPBody:postData];
NSMutableURLRequest
HeaderField 값을 추가 할 수 있습니다 .
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setValue:VALUE forHTTPHeaderField:@"cookie"];
이것은 나를 위해 일하고 있습니다.
샘플 코드
- (void)reqUserBalance:(NSString*)reward_scheme_id id:(NSString*)user_id success:(void (^)(id responseObject))success failure:(void (^)(id responseObject))failure{
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@reward/%@/user/%@/balance",URL_SERVER,reward_scheme_id,user_id]];
NSLog(@"%@",url);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"true" forHTTPHeaderField:@"Bypass"];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
{
options:kNilOptions error:NULL];
if (data.length > 0 && connectionError == nil)
{
NSDictionary * userPoints = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
NSString * points = [[userPoints objectForKey:@"points"] stringValue];
NSLog(@"%@",points);
[SecuritySetting sharedInstance].usearAvailablePoints = points;
}
}];
}