【问题标题】:URLSession returns HTTP 403 error pageURLSession 返回 HTTP 403 错误页面
【发布时间】:2017-07-22 01:03:50
【问题描述】:

我正在尝试在 Swift 中运行 HTTP 请求,以将 2 个参数发布到 URL。 但是总是返回403错误页面,这是怎么回事?

我尝试添加 Content-type 标头,但它不起作用。

代码:

    print("ENVIAR DATOS")

    let url = NSURL(string: "https://www.portaljuridico.com.co/portaljuridico/User/login")

    let request = NSMutableURLRequest(url: url! as URL)
    request.httpMethod = "POST"

    let param = ["username" : "juan", "password" : "123"]
    guard let httpBody = try? JSONSerialization.data(withJSONObject: param, options: []) else { return }

    //request.addValue("application/form-data", forHTTPHeaderField: "Content-Type")
    //request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    //request.addValue("application/json", forHTTPHeaderField: "Accept")
    request.httpBody = httpBody

    let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
        guard let data = data, error == nil else {
            print("error = \(error!)")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response!)")
        }

        let responseString = String(data: data, encoding: .utf8)
        print("responseString = \(responseString!)")
    }

    task.resume()

【问题讨论】:

  • 使用 postString 作为字典而不是字符串。也用试试? JSONSerialization.data(withJSONObject: postString, options: .prettyPrinted)
  • 我刚刚更新了它仍然无法正常工作:(
  • 服务器以自己的方式接受 POST 数据。您的服务器接受什么样的数据?它真的接受 JSON 吗?

标签: swift post httprequest nsurlsession http-status-code-403


【解决方案1】:

端点似乎是http://www.portaljuridico.com.co/portaljuridico/User/loginUser,并在无效的用户/密码上重定向到http://www.portaljuridico.com.co/portaljuridico/Login

【讨论】:

    猜你喜欢
    • 2015-01-18
    • 1970-01-01
    • 2011-03-08
    • 2020-11-20
    • 2020-07-07
    • 2018-12-26
    • 1970-01-01
    • 2018-11-17
    • 2021-01-26
    相关资源
    最近更新 更多