【问题标题】:Why might I be getting an internal server error (500) on this http POST request为什么我可能会在此 http POST 请求上收到内部服务器错误 (500)
【发布时间】:2017-07-05 08:45:56
【问题描述】:

我已经为此奋斗了好多年。我正在尝试将图像上传到服务器,但不断收到 500 错误。

这是我用来获取图像的代码,对其进行base64编码,然后将其添加到字典中。

 if let imageDataToUpload = UIImageJPEGRepresentation(selectedImage, 1.0) {


            let encodedImageData = imageDataToUpload.base64EncodedString(options: [])

            let extras = "data:image/jpeg;base64,"

            let postBody = [
                "image": extras + encodedImageData,
                "id": id,
                "instruction": "1",
                "ext": ""
            ]

            let endPoint = UrlFor.uploadPhoto

            ApiManager().apiPostImage(endPoint: endPoint, postBody: postBody, callBackFunc: handleResultOfUploadPhoto) }

这是我用来执行实际 POST 请求的代码。您会注意到我正在尝试将帖子正文转换为 JSON 对象。

func apiPostImage(endPoint: String, postBody: [String: Any]?, callBackFunc: @escaping (ResultOfApiCall) -> Void) {

    // get the sessionKey
    guard let sessionKey = KeyChainManager().getSessionKey() else {
        print("error getting session key")
        AppDelegate().signUserOut()
        return
    }

    // create a url with above end point and check its a valid URL
    guard let url = URL(string: endPoint) else {
        print("Error: cannot create URL")
        return
    }

    // set up the request
    var urlRequest = URLRequest(url: url)
    urlRequest.httpMethod = "POST"

    if let postBody = postBody {
        do {
            try urlRequest.httpBody = JSONSerialization.data(withJSONObject: postBody, options: [])
        } catch {
            print("problems creating json body")
        }
    }

    // set up the header
    let config = URLSessionConfiguration.default
    config.httpAdditionalHeaders = [
        "Accept": "application/json",
        "apiKey": "0101010-0101010", // not the real apiKey
        "usrKey": sessionKey,
        "appInfo" : "appcode:1000|version:2.0.37",
        "Content-Type": "application/json"
    ]

    let session = URLSession(configuration: config)

    let task = session.dataTask(with: urlRequest, completionHandler:
        { (data: Data?, response: URLResponse?, error: Error?) -> Void in

            let (noProblem, ResultOfCall) = self.checkIfProblemsWith(data: data, response: response, error: error)

            guard noProblem else {
                callBackFunc(ResultOfCall)
                return
            }

            let serializedData: [String:Any]
            do {

                // safe bc checked for nil already.
                serializedData = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]

            } catch  {

                callBackFunc(ResultOfApiCall.errorWhileSerializingJSON)
                return
            }

            // pass serialized data back using the callBackFunc
            callBackFunc(ResultOfApiCall.success(serializedData))
    })

    task.resume()
}

API 是 RESTful。我无权访问 API 错误日志,但我从 API 收到此错误:

["codesc": GENERALERROR, "code": 5001, "msg": Conversion from string "Optional(1004007)" to type 'Double' is not valid.]

【问题讨论】:

  • 你也在上传什么后端?您可以访问错误日志吗?你得到什么回应?尝试使用 Chrome 的邮递员应用程序将请求复制到后端,如果它在那里工作,那么你知道问题出在 swift 代码上。这里没有足够的信息来提供准确的答案
  • @Scriptable 它是一个 RESTful 网络服务。不,我无权访问错误日志。我收到此错误:来自 500 错误的数据:["codesc": GENERALERROR, "code": 5001, "msg": Conversion from string "Optional(1004007)" to type 'Double' is not valid.] 我会更新我对此信息的疑问。
  • 在使用任何其他 REST 客户端进行 api 调用时,您是否得到正确的结果?

标签: ios json swift post urlsession


【解决方案1】:

500 Internal Server Error 是服务器端错误,这意味着问题可能不在于您的计算机或互联网连接,而是网站服务器的问题。

【讨论】:

    【解决方案2】:
    var  task = URLSession().uploadTask(with: urlRequest, from: imageData) { (data , response , error) in
            // Check Response here
        })
    

    task.resume()

    您发送的数据是可选值,请确保您传递的数据不是可选值。

    【讨论】:

      【解决方案3】:

      好的,我想通了。感谢@Scriptable 推动我深入挖掘返回的错误消息。

      似乎 API 期望其中一个属性是双精度的,即 id 属性,但我传入的是一个字符串。

      我还必须将 postBody Dictionary 从可选更改为非可选。

      改变了这个,它解决了这个问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-27
        相关资源
        最近更新 更多