HttpRequest.swift 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. //
  2. // HttpRequest.swift
  3. // Swifter
  4. // Copyright (c) 2015 Damian Kołakowski. All rights reserved.
  5. //
  6. import Foundation
  7. public struct HttpRequest {
  8. public enum Method: String {
  9. case GET, POST, PUT, DELETE
  10. }
  11. public let url: String
  12. public let urlParams: [(String, String)]
  13. public let method: Method
  14. public let headers: [String: String]
  15. public let body: [UInt8]?
  16. public var address: String?
  17. public var params: [String: String]
  18. public func parseUrlencodedForm() -> [(String, String)] {
  19. guard let body = body, let contentTypeHeader = headers["content-type"] else {
  20. return []
  21. }
  22. let contentTypeHeaderTokens = contentTypeHeader.split(";").map { $0.trim() }
  23. guard let contentType = contentTypeHeaderTokens.first where contentType == "application/x-www-form-urlencoded" else {
  24. return []
  25. }
  26. return UInt8ArrayToUTF8String(body).split("&").map { (param: String) -> (String, String) in
  27. let tokens = param.split("=")
  28. if let name = tokens.first, value = tokens.last where tokens.count == 2 {
  29. return (name.replace("+", new: " ").removePercentEncoding(),
  30. value.replace("+", new: " ").removePercentEncoding())
  31. }
  32. return ("","")
  33. }
  34. }
  35. public struct MultiPart {
  36. public let headers: [String: String]
  37. public let body: [UInt8]
  38. }
  39. public func parseMultiPartFormData() -> [MultiPart] {
  40. guard let body = body, let contentTypeHeader = headers["content-type"] else {
  41. return []
  42. }
  43. let contentTypeHeaderTokens = contentTypeHeader.split(";").map { $0.trim() }
  44. guard let contentType = contentTypeHeaderTokens.first where contentType == "multipart/form-data" else {
  45. return []
  46. }
  47. var boundary: String? = nil
  48. contentTypeHeaderTokens.forEach({
  49. let tokens = $0.split("=")
  50. if let key = tokens.first where key == "boundary" && tokens.count == 2 {
  51. boundary = tokens.last
  52. }
  53. })
  54. if let boundary = boundary where boundary.utf8.count > 0 {
  55. return parseMultiPartFormData(body, boundary: "--\(boundary)")
  56. }
  57. return []
  58. }
  59. private func parseMultiPartFormData(data: [UInt8], boundary: String) -> [MultiPart] {
  60. var generator = data.generate()
  61. var result = [MultiPart]()
  62. while let part = nextMultiPart(&generator, boundary: boundary, isFirst: result.isEmpty) {
  63. result.append(part)
  64. }
  65. return result
  66. }
  67. private func nextMultiPart(inout generator: IndexingGenerator<[UInt8]>, boundary: String, isFirst: Bool) -> MultiPart? {
  68. if isFirst {
  69. guard nextMultiPartLine(&generator) == boundary else {
  70. return nil
  71. }
  72. } else {
  73. nextMultiPartLine(&generator)
  74. }
  75. var headers = [String: String]()
  76. while let line = nextMultiPartLine(&generator) where !line.isEmpty {
  77. let tokens = line.split(":")
  78. if let name = tokens.first, value = tokens.last where tokens.count == 2 {
  79. headers[name.lowercaseString] = value.trim()
  80. }
  81. }
  82. guard let body = nextMultiPartBody(&generator, boundary: boundary) else {
  83. return nil
  84. }
  85. return MultiPart(headers: headers, body: body)
  86. }
  87. private func nextMultiPartLine(inout generator: IndexingGenerator<[UInt8]>) -> String? {
  88. var result = String()
  89. while let value = generator.next() {
  90. if value > Constants.CR {
  91. result.append(Character(UnicodeScalar(value)))
  92. }
  93. if value == Constants.NL {
  94. break
  95. }
  96. }
  97. return result
  98. }
  99. private func nextMultiPartBody(inout generator: IndexingGenerator<[UInt8]>, boundary: String) -> [UInt8]? {
  100. var body = [UInt8]()
  101. let boundaryArray = [UInt8](boundary.utf8)
  102. var matchOffset = 0;
  103. while let x = generator.next() {
  104. matchOffset = ( x == boundaryArray[matchOffset] ? matchOffset + 1 : 0 )
  105. body.append(x)
  106. if matchOffset == boundaryArray.count {
  107. body.removeRange(Range<Int>(start: body.count-matchOffset, end: body.count))
  108. if body.last == Constants.NL {
  109. body.removeLast()
  110. if body.last == Constants.CR {
  111. body.removeLast()
  112. }
  113. }
  114. return body
  115. }
  116. }
  117. return nil
  118. }
  119. }