将Http请求发送到.Net服务器

时间:2018-04-24 05:51:35

标签: ios swift http alamofire

我想将帖子请求发送到.Net服务器。有我的帖子请求代码:

  public func SendPostHttpRequest(baseURL: String, parameter: [String:Any], closure:@escaping ((_ success:JSON,_ error:NSError?) -> Void)) {
    let manager = Alamofire.SessionManager.default
    if let url = URL(string: baseURL) {
      var urlRequest = URLRequest(url: url)
      urlRequest.setValue("text/html; charset=utf-8", forHTTPHeaderField: "Content-Type")
      urlRequest.setURLEncodedFormData(parameters: parameter)
      manager.request(urlRequest).responseString { response in
        debugPrint(" HTML error -------> \(response)")
      }
      manager.request(urlRequest).responseJSON { response in
        switch response.result {
        case .success(let JSON) :
          closure(JSON,nil)
        case .failure(let error):
          closure(nil,error as NSError)
          debugPrint("get error ---> \((error.localizedDescription)) ")
        }
      }
    }
  }

即定义URLEncodedFormData的扩展以请求

 extension URLRequest {
        private static let alloweCharacters = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789  -_.*@$!#/:+[]\n")
          public mutating func setURLEncodedFormData(parameters: [String: Any]) {
            var encodedParameters = ""
            for (key, value) in parameters {

              if !encodedParameters.isEmpty {
                encodedParameters += "&"
              }
              encodedParameters += URLRequest.urlEncoded(value: key) ?? ""
              encodedParameters += "="

              let valuee = value
              if let boolValue = valuee as? Bool {
                encodedParameters += "\(boolValue)"
              }
              if let intValue = valuee as? Int {
                encodedParameters += "\(intValue)"
              }
              if let stringValue = valuee as? String {
                encodedParameters += (URLRequest.urlEncoded(value: stringValue) ?? "")
              }
            }
            self.httpMethod = "POST"
            self.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
            self.httpBody = encodedParameters.data(using: .utf8)
          }

          private static func urlEncoded(value: String?) -> String? {

            return value?.addingPercentEncoding(withAllowedCharacters: alloweCharacters)!.replacingOccurrences(of: " ", with: "")
          }
        }

我在向服务器发送不同类型的变量时遇到问题。 在服务器端我收到此错误: 对象引用未设置为对象的实例。

我认为因为我将所有参数发送到字符串,服务器端没有找出bool和整数变量。

这是请求对象类,我现在的问题是整数whit的参数类型setURLEncodedFormData方法作为整数类型发送到服务器还是String?

class RegisterRequest: NSObject {
  var Usertoken: String!
  var ProffessionId: Int?
  override init() {
    self.Usertoken = ""
    self.ProvinceId = nil
}
}

0 个答案:

没有答案