在Swift中发送简单的POST,获取"Empty Post"回复 [英] Sending simple POST in Swift, getting "Empty Post" response

查看:81
本文介绍了在Swift中发送简单的POST,获取"Empty Post"回复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Swift中编写iOS应用程序中的注册页面.我要测试的第一件事是发送带有电子邮件地址的POST,这是我这样做的方式:

I have registration page in my iOS app that I'm trying to write in Swift. The first thing I'm testing out is sending a POST with the email address, this is the way I'm doing so:

var bodyData = ("userEmail=%@\" \" &userPassword=%@\" \"&userDevice=%@\" \"", emailAddress.text, password.text, deviceModel)

    let dataToSend = (bodyData as NSString).dataUsingEncoding(NSUTF8StringEncoding)

            request.HTTPMethod = "POST"
            request.HTTPBody = dataToSend
            let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
                data, response, error in

                if error != nil {
                    print("error=\(error)")
                    return
                }
                // print("response = \(response)")

                let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("responseString = \(responseString)")
            }
            task.resume()

但是,我收到一条消息,指出那是一个空的帖子.这是上面输出的确切响应:responseString = Optional({"complete":"false","message":"Empty Post"}) 我研究了在Swift中发送简单POST的不同方法,这似乎是正确的.我看不到任何错误,也看不到为什么它会输出一条消息,指出该帖子为空...也许除了字符串的格式以外?

However, I'm getting a message back stating that it was an empty post. This is the exact response from the output above: responseString = Optional({"complete":"false","message":"Empty Post"}) I've researched different ways to send a simple POST in Swift, and this appears to be correct. I can't see anything wrong with it or why it would output a message saying that the post was empty... Except for maybe the format of the string?

该数据库期望新用户"服务有多种功能,由于它只是一项测试,因此我只发送了一部分.这可能是问题吗?新用户服务期望:

The database is expecting multiple things for the "new user" service, and I'm only sending one part due to it being a test. Could this be the issue? The new-user service is expecting:

Service URL : https://test.com/services/new-user/
Required Post Fields:
For New User:
'userEmail'
'userPassword'
'userDevice'

(来自文档).

我没有太多使用Web服务.经过更多的集思广益后,我认为这可能是罪魁祸首:我可能会得到响应,因为我没有一次发送所有数据.我也可能发送不正确.我可以将其以文本形式发送还是需要以JSON形式发送?

I haven't worked with web services much. After brainstorming more I think these may be the culprits: I may be getting the response back because I'm not sending all the data at once. I also may be sending it incorrectly. Can I send it as text or do I need to send it as JSON?

推荐答案

几个问题:

  1. 您的一行显示:

  1. You have a line that says:

var bodyData = ("userEmail=%@\" \" &userPassword=%@\" \"&userDevice=%@\" \"", emailAddress.text, password.text, deviceModel)

那并没有达到您的预期.它正在创建一个包含四个项的元组,其中四个项由格式字符串和三个值组成,而不是单个格式的字符串.打印bodyData,您会明白我的意思.

That does not do what you intended. It's creating a tuple with four items that consists of a format string and three values, not a single formatted string. Print the bodyData and you'll see what I mean.

您要么想使用String(format: ...),要么甚至更简单地使用字符串插值. (请参见下面的代码段.)

You either want to use String(format: ...), or even easier, use string interpolation. (See code snippet below.)

假定emailAddresspasswordUITextField对象,请注意text属性是可选的,因此在使用它们之前,必须将其打开.查看bodyData字符串,您会明白我的意思.

Assuming that emailAddress and password are UITextField objects, note that the text property is optional, so you have to unwrap those optionals before you use them. Look at the bodyData string and you'll see what I mean.

我也不知道deviceModel是否也是可选的,但如果是,也将其解包.

I don't know if deviceModel was optional as well, but if so, unwrap that, too.

您在请求的userPassword参数之前有一个空格.这将使它的格式不正确.删除该空间.您也可以通过删除一堆这些\"引用来简化该格式字符串.

You have a space right before the userPassword parameter of the request. That will make it not well formed. Remove that space. You can probably simplify that format string by getting rid of a bunch of those \" references, too.

您可能应该指定请求的Content-Type.通常没有必要,但这是一个好习惯.

You probably should be specifying the Content-Type of the request. It's often not necessary, but it's good practice.

您显然会收到JSON响应,因此您可能想解析它.

You're clearly getting a JSON response, so you might want to parse it.

因此,您可能会执行以下操作:

Thus, you might do something like:

guard emailAddress.text != nil && password.text != nil else {
    print("please fill in both email address and password")
    return
}

// use 
//
// let bodyString = String(format: "userEmail=%@&userPassword=%@&userDevice=%@", emailAddress.text!, password.text!, deviceModel)
//
// or use string interpolation, like below:

let bodyString = "userEmail=\(emailAddress.text!)&userPassword=\(password.text!)&userDevice=\(deviceModel)"

let bodyData = bodyString.dataUsingEncoding(NSUTF8StringEncoding)

request.HTTPMethod = "POST"
request.HTTPBody = bodyData
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
    guard error == nil && data != nil else {
        print("error=\(error)")
        return
    }

    do {
        let responseObject = try NSJSONSerialization.JSONObjectWithData(data!, options: [])

        print(responseObject)
    } catch let parseError as NSError {
        print(parseError)
    }
}
task.resume()

请注意,您实际上也应该对要添加到正文中的值进行百分比转义(特别是,如果这些值中可能包含空格,+&或其他保留字符).参见 https://stackoverflow.com/a/28027627/1271826 .

Note, you really should be percent-escaping the values you are adding to the body, too (notably, if the values might have spaces, +, &, or other reserved characters in them). See https://stackoverflow.com/a/28027627/1271826.

如果您不想陷入此类杂草,请考虑使用类似 Alamofire之类的框架,它会为您处理这些事情.例如:

If you don't want to get into the weeds of this sort of stuff, consider using a framework like Alamofire, which takes care of this stuff for you. For example:

guard emailAddress.text != nil && password.text != nil else {
    print("please fill in both email address and password")
    return
}

let parameters = [
    "userEmail" : emailAddress.text!,
    "userPassword" : password.text!,
    "userDevice" : deviceModel
]

Alamofire.request(.POST, urlString, parameters: parameters)
    .responseJSON { response in
        switch response.result {
        case .Failure(let error):
            print(error)
        case .Success(let value):
            print(value)
        }
}

这篇关于在Swift中发送简单的POST,获取"Empty Post"回复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆