Làm thế nào để bạn truy xuất tất cả tiêu đề HTTP từ một số NSURLRequest
trong Mục tiêu-C?Cách lấy tiêu đề HTTP
Trả lời
này thuộc dễ dàng, nhưng không rõ ràng lớp của các vấn đề lập trình iPhone. Xứng đáng với bài đăng nhanh:
Tiêu đề cho kết nối HTTP được bao gồm trong lớp NSHTTPURLResponse
. Nếu bạn có biến số NSHTTPURLResponse
, bạn có thể dễ dàng lấy tiêu đề ra dưới dạng NSDictionary
bằng cách gửi thông báo allHeaderFields.
Đối với yêu cầu đồng bộ - không được khuyến khích, bởi vì họ chặn - nó dễ dàng để cư một NSHTTPURLResponse
:
NSURL *url = [NSURL URLWithString:@"http://www.mobileorchard.com"];
NSURLRequest *request = [NSURLRequest requestWithURL: url];
NSHTTPURLResponse *response;
[NSURLConnection sendSynchronousRequest: request returningResponse: &response error: nil];
if ([response respondsToSelector:@selector(allHeaderFields)]) {
NSDictionary *dictionary = [response allHeaderFields];
NSLog([dictionary description]);
}
Với một yêu cầu không đồng bộ bạn phải làm một công việc ít hơn. Khi gọi lại connection:didReceiveResponse:
được gọi, nó được chuyển thông số NSURLResponse
làm thông số thứ hai. Bạn có thể bỏ nó vào một NSHTTPURLResponse
như vậy:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
if ([response respondsToSelector:@selector(allHeaderFields)]) {
NSDictionary *dictionary = [httpResponse allHeaderFields];
NSLog([dictionary description]);
}
}
YourViewController.h
@interface YourViewController : UIViewController <UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *yourWebView;
@end
YourViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
//Set the UIWebView delegate to your view controller
self.yourWebView.delegate = self;
//Request your URL
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://website.com/your-page.php"]];
[self.legalWebView loadRequest:request];
}
//Implement the following method
- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSLog(@"%@",[webView.request allHTTPHeaderFields]);
}
Với NSURLConnection
bị phản đối từ iOS 9, bạn có thể sử dụng một NSURLSession
để có được kiểu MIME thông tin từ một NSURL
hoặc NSURLRequest
.
Bạn yêu cầu phiên truy xuất URL, sau đó khi nhận được NSURLResponse
đầu tiên (có chứa thông tin loại MIME) trong cuộc gọi đại biểu, bạn hủy phiên để ngăn tải xuống toàn bộ URL.
Dưới đây là một số xương trần đang Swift nào đó:
/// Use an NSURLSession to request MIME type and HTTP header details from URL.
///
/// Results extracted in delegate callback function URLSession(session:task:didCompleteWithError:).
///
func requestMIMETypeAndHeaderTypeDetails() {
let url = NSURL.init(string: "https://google.com/")
let urlRequest = NSURLRequest.init(URL: url!)
let session = NSURLSession.init(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration(), delegate: self, delegateQueue: NSOperationQueue.mainQueue())
let dataTask = session.dataTaskWithRequest(urlRequest)
dataTask.resume()
}
//MARK: NSURLSessionDelegate methods
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
// Cancel the rest of the download - we only want the initial response to give us MIME type and header info.
completionHandler(NSURLSessionResponseDisposition.Cancel)
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?)
{
var mimeType: String? = nil
var headers: [NSObject : AnyObject]? = nil
// Ignore NSURLErrorCancelled errors - these are a result of us cancelling the session in
// the delegate method URLSession(session:dataTask:response:completionHandler:).
if (error == nil || error?.code == NSURLErrorCancelled) {
mimeType = task.response?.MIMEType
if let httpStatusCode = (task.response as? NSHTTPURLResponse)?.statusCode {
headers = (task.response as? NSHTTPURLResponse)?.allHeaderFields
if httpStatusCode >= 200 && httpStatusCode < 300 {
// All good
} else {
// You may want to invalidate the mimeType/headers here as an http error
// occurred so the mimeType may actually be for a 404 page or
// other resource, rather than the URL you originally requested!
// mimeType = nil
// headers = nil
}
}
}
NSLog("mimeType = \(mimeType)")
NSLog("headers = \(headers)")
session.invalidateAndCancel()
}
Tôi đã đóng gói chức năng tương tự trong dự án URLEnquiry tại github mà làm cho nó một chút dễ dàng hơn để thực hiện các truy vấn trong-line với nhiều loại MIME và Tiêu đề HTTP. URLEnquiry.swift là tệp quan tâm có thể được đưa vào dự án của riêng bạn.
Phiên bản Swift sử dụng Alamofire để có hiệu quả. Đây là những gì đã làm việc cho tôi:
Alamofire.request(YOUR_URL).responseJSON {(data) in
if let val = data.response?.allHeaderFields as? [String: Any] {
print("\(val)")
}
}
- 1. Tiêu đề HTTP tiêu đề và nnCoection
- 2. Nén tiêu đề Http
- 3. "Tiêu đề HTTP thô" là gì? Sự khác biệt giữa "tiêu đề HTTP" và "tiêu đề HTTP thô" là gì?
- 4. Cách gửi tiêu đề HTTP trong java
- 5. HTTP: Tạo tiêu đề ETAG
- 6. redirect_to với tiêu đề HTTP
- 7. Tiêu đề phạm vi HTTP
- 8. PHP remove tiêu đề HTTP
- 9. đọc http post tiêu đề
- 10. Tiêu đề HTTP - ntCoent-Length
- 11. Làm cách nào tôi có thể lấy địa chỉ IP từ tiêu đề HTTP trong Java
- 12. Phân tích cú pháp tiêu đề HTTP
- 13. Tiêu đề HTTP tùy chỉnh ở Django
- 14. NSURLYêu cầu đặt tiêu đề HTTP
- 15. render_to_response với tiêu đề phản hồi HTTP
- 16. SP Char trong tiêu đề HTTP?
- 17. Nhiều tiêu đề Set-cookie trong HTTP
- 18. Sử dụng Accept-charset tiêu đề HTTP
- 19. tiêu đề 404 - HTTP 1.0 hoặc 1.1?
- 20. Tiêu đề yêu cầu HTTP: Biến UserAgent
- 21. Xem tiêu đề HTTP trong Google Chrome?
- 22. Gửi tiêu đề http với python
- 23. cách thêm tiêu đề http vào soaprequest trong java
- 24. Cách chuyển tiếp tiêu đề trên chuyển hướng HTTP
- 25. Cách thêm tiêu đề http vào suds 0.3.6?
- 26. Cách xác định "tiêu đề yêu cầu http" trong OpenURI
- 27. Làm cách nào để xóa tiêu đề phản hồi HTTP?
- 28. Hoạt động xà phòng WCF trong tiêu đề HTTP hoặc tiêu đề SOAP?
- 29. Cách lấy tiêu đề của chế độ xem tiêu đề của phần khi chọn một ô
- 30. Lấy dữ liệu HTTP thô (Tiêu đề, Cookie, v.v.) trong Google Cloud Endpoints
Nếu bạn chỉ muốn tìm nạp tiêu đề phản hồi http, sau đó đăng yêu cầu HEAD. Yêu cầu HEAD sẽ không tìm nạp nội dung phản hồi. Ví dụ - Đặt loại Phương thức Http theo yêu cầu. NSMutableURLRequest * mutableRequest = [[NSMutableURLRequest alloc] initWithURL: url]; mutableRequest.HTTPMethod = @ "HEAD"; – Omkar
Tại sao chúng ta nên đưa NSURLResponse vào NSHTTPURLResponse? – youssman
Điều này không * ghi * tất cả các tiêu đề được gửi trong yêu cầu! Nếu bạn đặt tiêu đề bổ sung cho NSURLSessionConfiguration, những tiêu đề đó sẽ không được ghi lại. Tôi chưa tìm được cách lấy chúng từ phản hồi ... – Johanneke