所以,我必须使用方法来处理 Web 服务:
获取:
- (NSDictionary *)getDataFromURL:(NSString*)url {
NSString * serverAddress =[NSString stringWithFormat:url,mySchoolURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL
URLWithString:serverAddress]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10
];
[request setHTTPMethod: @"GET"];
NSError *requestError = nil;
NSURLResponse *urlResponse = nil;
NSData *response = [NSURLConnection
sendSynchronousRequest:request
returningResponse:&urlResponse
error:&requestError];
NSError* error = nil;
NSDictionary *output = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:nil];
return output;
}
和一个 POST:
-(NSData*)postData:(NSDictionary*)requestData toUrl:(NSString*)destination {
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:requestData options:0 error:&error];
NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postdata length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:destination,mySchoolURL]]];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postdata];
[request setHTTPMethod:@"POST"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
return nil;
}
不知何故,POST 方法的 HTTP header 确实包含 cookie 的 SessionID,而 GET 方法则没有。
我不得不承认我并不完全了解 cookie 等的内部结构,但是网络上的一些消息来源声称我根本不应该担心 cookie,因为它们是自动处理的。
无论如何,我正在与之交谈的 Web 服务在 POST 和 GET 情况下都需要一个 session ID,所以现在我不得不开始了解发生了什么。
你们中有人能帮帮我吗? 具体问题是:如何使用 GET 方法将 Session_ID 传递给 URL? 提前致谢
最佳答案
好的,一种方法是将 cookie 添加到 HTTP header 中。执行此操作时,URL 的正确性是关键。如果协议(protocol)错误,则可能无法包含某些 cookie。您将需要获取所有可用的 cookie,然后使用可用的 cookie 为 header 创建一个字典。然后您只需通过调用 setAllHTTPHeaderFields: 将这些 header 添加到您的请求中。我在下面放置了一个如何执行此操作的简单示例,但是您可以在 the Apple Documentation Class Reference 了解有关 cookie 工作原理的更多信息。
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:request.URL];
NSDictionary *headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
[request setAllHTTPHeaderFields:headers];
我真的希望这对你有所帮助。我建议您阅读 Apples 文档以尽可能多地帮助您。祝你好运!
关于ios - 将 session ID 传递给 GET Objective-C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34779379/