REST API 的问题



我在iOS application中的REST API's工作。

我已经测试了POST方法的Server URLParameters

它正在用

返回

您的浏览器发送了该服务器无法理解

的请求

响应中的错误。

GET请求API工作正常。如果有人面对同样的问题,请告诉我。

谢谢。

请检查我的Web服务模型

let configuration = URLSessionConfiguration.default;
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: nil)
var urlString = String()
urlString.append(Constant.BASE_URL)
urlString.append(methodName)
let encodedUrl = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
let serverUrl: URL = URL(string: (encodedUrl?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed))!)!
var request : URLRequest = URLRequest(url: serverUrl, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 60.0)
var paramStr : String = String()
if requestDict.count > 0 {
    let keysArray = requestDict.keys
    for  key in keysArray {
        if paramStr.isEmpty{
            paramStr.append("(key)=(requestDict[key]! as! String)")
        }else{
            paramStr.append("&(key)=(requestDict[key]! as! String)")
        }
    }
}
let postData:Data = try! JSONSerialization.data(withJSONObject: requestDict)//paramStr.data(using: .utf8)!
let reqJSONStr = String(data: postData, encoding: .utf8)
let postLength = "(postData.count)"
request.httpMethod = "POST"
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
//request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
//request.httpBody = reqJSONStr?.data(using: .utf8)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try! JSONSerialization.data(withJSONObject: requestDict)

if  headerValue != nil{
    let allkeys = headerValue.keys
    for key in allkeys {
        request.setValue(headerValue[key] as! String?, forHTTPHeaderField: key)
    }
}
let postDataTask : URLSessionDataTask = session.dataTask(with: request, completionHandler:
{
    data, response, error in
    if data != nil && error == nil{
        let res = String(data: data!, encoding: .utf8)
        let dict = convertToDictionary(text: res!)
        if let httpResponse = response as? HTTPURLResponse {
            //print("error (httpResponse.statusCode)")
            if httpResponse.statusCode == 200
            {
                DispatchQueue.main.async {
                    successBlock (response!,(dict)!)
                }
            }
            else
            {
                if (error?.localizedDescription) != nil
                {
                    errorBlock((error?.localizedDescription)! as String)
                }
                else
                {
                    errorBlock("")
                }
            }
        }
        else
        {
            errorBlock((error?.localizedDescription)! as String)
        }
    }
    else{
        if let httpResponse = error as? HTTPURLResponse {
            //print("error (httpResponse.statusCode)")
        }
        errorBlock((error?.localizedDescription)! as String)
    }
})
postDataTask.resume()

假设您的后端期望表单纯编码的请求,那么您应该在字符串URL编码

中转换参数字典

这是一个示例

let parameters : [String:Any] = ["ajax":1,"test":"abuela"]
var queryItems : [URLQueryItem] = []
for key in parameters.keys {
    if let value = parameters[key] as? String {
        queryItems.append(URLQueryItem(name: key, value: value))
    }else{
        queryItems.append(URLQueryItem(name: key, value: String(describing:parameters[key]!)))
    }
}
var urlComponents = URLComponents()
urlComponents.queryItems = queryItems

然后,如果您

print(urlComponents.percentEncodedQuery!)

您会得到

test=abuela&ajax=1

然后,您需要添加urlString

urlString.append("&" + urlComponents.percentEncodedQuery!)

完整代码

let configuration = URLSessionConfiguration.default;
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: nil)
var urlString = String()
urlString.append(Constant.BASE_URL)
urlString.append(methodName)
var queryItems : [URLQueryItem] = []
for key in parameters.keys {
    if let value = parameters[key] as? String {
        queryItems.append(URLQueryItem(name: key, value: value))
    }else{
        queryItems.append(URLQueryItem(name: key, value: String(describing:parameters[key]!)))
    }
}
var urlComponents = URLComponents()
urlComponents.queryItems = queryItems
print(urlComponents.percentEncodedQuery!)
urlString.append("&" + urlComponents.percentEncodedQuery!)
let encodedUrl = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
let serverUrl: URL = URL(string: urlString)!
var request : URLRequest = URLRequest(url: serverUrl, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 60.0)

request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let postDataTask : URLSessionDataTask = session.dataTask(with: request, completionHandler:
{
    data, response, error in
    if data != nil && error == nil{
        let res = String(data: data!, encoding: .utf8)
        let dict = convertToDictionary(text: res!)
        if let httpResponse = response as? HTTPURLResponse {
            //print("error (httpResponse.statusCode)")
            if httpResponse.statusCode == 200
            {
                DispatchQueue.main.async {
                    successBlock (response!,(dict)!)
                }
            }
            else
            {
                if (error?.localizedDescription) != nil
                {
                    errorBlock((error?.localizedDescription)! as String)
                }
                else
                {
                    errorBlock("")
                }
            }
        }
        else
        {
            errorBlock((error?.localizedDescription)! as String)
        }
    }
    else{
        if let httpResponse = error as? HTTPURLResponse {
            //print("error (httpResponse.statusCode)")
        }
        errorBlock((error?.localizedDescription)! as String)
    }
})
postDataTask.resume()

如果您的后端正在等待application/json HTTP主体编码

您正在通过HTTPBody中的JSON对象传递一个JSON对象,但是您的ContentType标题是错误的,而不是"application/x-www-form-urlencoded"应该是"application/json",我认为您的JSON转换是错误的,尝试直接使用您的请求dick,并且JSONSerialization将在有效的JSON对象中转换您的字典,可以在您的request.httpBody

中使用

替换

request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

request.setValue("application/json", forHTTPHeaderField: "Content-Type")

使用此操作将其转换为JSON您的请求参数字典

request.httpBody = try! JSONSerialization.data(withJSONObject: requestDict)

相关内容

  • 没有找到相关文章

最新更新