使用Alamofire发送带字符串格式的Http Post请求

时间:2017-05-06 12:41:16

标签: ios swift alamofire

我想在我的项目中使用Alamofire,有自己的代码用于向服务器发送请求,这样做很好,但是当使用Alamofire总是获得超时响应时,如何使用http标头发送请求:“application / x-www -form-urlencoded“在Alamofire。

这是我的要求:

func fetchRequest(completion: @escaping (RequestResult) -> Void){

        let myUrl = NSURL(string: stringForUrl)
        var request = URLRequest(url: myUrl as! URL )

 let param = ["userid":"59","key":"sofah@#^!*FDS#","action":"vitrin","step":"list","sort": "","filter":"","start":String(""),"end":String("")]

        request.setURLEncodedFormData(parameters: params as! [String : String])


        let task = session.dataTask(with: request, completionHandler: {
            (data, response, error)  in

            let httpResponse = response as? HTTPURLResponse

            if  httpResponse == response as? HTTPURLResponse {

                guard let data = data else {


                    print("No data in server")
                    return
                }

                let responseString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
                print("responseString = \(responseString)")

                let statusCode = httpResponse?.statusCode
                print(statusCode ?? "")
            }


            let result = self.processRequest(data: data, error: error as NSError?)

            // completion closure that will be called once the web service request is completed.
            completion(result)
        })
        task.resume()
    }

extension URLRequest {

  private static let alloweCharacters = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 -_.*@$!#")

  public mutating func setURLEncodedFormData(parameters: [String: String?])  {

    var encodedParameters = ""

    for (key, value) in parameters {

      if !encodedParameters.isEmpty {
        encodedParameters += "&"
      }

      encodedParameters += URLRequest.urlEncoded(value: key)
      encodedParameters += "="

      if let valuee = value {
        encodedParameters += URLRequest.urlEncoded(value: valuee)
      }
    }

    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: "+")
  }

}

发送请求使用Alamofire:

 func sendRequestUsingAlamofire() {


    let param = ["userid":"59" ,"key":"sofah@#^!*FDS#","action":"vitrin","step":"list","sort": "","filter":"","start":String(""),"end":String("")]

    let url =  "http://www.***/service/index.php"


    let ulrRequest =  NSURL(string:url)
    var request = URLRequest(url: ulrRequest as! URL )


    request.setURLEncodedFormData(parameters: param as! [String : String])

        Alamofire.request(request).responseJSON(completionHandler: { (response) in

          switch (response.result) {
          case .success:
            //do json stuff
            break
          case .failure(let error):

            print(error)
            if error._code == NSURLErrorTimedOut {
              //timeout here
            }
            print("\n\nAuth request failed with error:\n \(error)")
            break
          }


        })

  }

使用Alamofire时我的问题在哪里? 谢谢

0 个答案:

没有答案