Swift 3无法弄清楚我的http放不起作用

时间:2017-01-26 10:36:16

标签: xcode http swift3 request http-put

我正在尝试向我的服务器发送一个put请求但是我得到的响应很奇怪。

如果我将此添加到邮递员:

{
            "firstName": req.body.firstName,
            "lastName": req.body.lastName,
            "email": req.body.email,
            "role": req.body.role,
            "birthday": new Date(req.body.birthday),
            "sex": req.body.sex,
            "password": pw
}

我从服务器获得200。但是在我的Swift应用程序中,我得到了500。

我的Put方法如下所示:

func putUser(accessToken: String, refreshToken: String, emailCurrent: String, firstName: String, lastName: String, emailNew: String,
                 role: Int, sex: String, password: String){

        print("vi kører putUser med denne accessToken \(accessToken) og refreshToken \(refreshToken)")

        let urlPath = "http://xxxxxxxxxxxxxx/api/users/user/\(emailCurrent)"
        let url = NSURL(string: urlPath)
        let session = URLSession.shared
        let request = NSMutableURLRequest(url: url as! URL)
        request.addValue(accessToken, forHTTPHeaderField: "accessToken")
        request.addValue(refreshToken, forHTTPHeaderField: "refreshToken")
        request.httpMethod = "PUT"



        let postString = "firstName=\(firstName)&lastName=\(lastName)&email=\(emailNew)&role=\(role)&birthday=2010-09-08&sex=\(sex)&password=\(password)"



     //   let strinng = "firstName=\(firstName)&lastName=\(lastName)&email\(emailNew)&role=\(role)&birthday=2010-09-08&sex=\(sex)&password=\(password)"

        print()
        print()

        print("Here is postString from putUser: \(postString)")

        request.httpBody = postString.data(using: String.Encoding.utf8)



        let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
            print("Task completed \(data) and response is xxxx")

//            print all info as a string. ---
                        let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
                        print("responseString = \(responseString!)")



        })
        task.resume()

    }

我得到的回复数据如下:

Here is postString from putUser:
firstName=abcd&lastName=bb&email=abc@gmail.com&role=1&birthday=2010-09-08&sex=female&password=123
Task completed Optional(169 bytes) and response is xxxx
responseString = <!DOCTYPE html><html><head><title></title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>Unexpected token f</h1><h2></h2><pre></pre></body></html>

我感觉这是因为我的postString,但我看不出邮差中的httpBody和上面的那个之间的区别。

提前致谢!

2 个答案:

答案 0 :(得分:0)

格式化HTTPBody的方式是错误的 您需要创建(NS)Dictionary 然后,您可以使用(NS)JSONSerialization(NS)Dictionary转换为JSON (NS)Data
您可以通过调用(NS)String(data:encoding:)来检查格式。

此外,您可能需要通过添加标题“Content-Type”:“application / json”来告诉服务器您正在提供JSON。 我们还经常添加长度:“Content-Length”:“lengthOfTheParametersData”。

在Objective-C中(我不使用Swift),但应该很容易翻译:

// PUT参数

NSDictionary *putParams = @{@"firstName":@"abcd",
                            @"lastName":@"bb",
                            @"email":@"abc@gmail.com",
                            @"role":@"1",
                            @"birthday":@"2010-09-08",
                            @"sex":@"female",
                            @"password":@"123"};
NSData *putData = [NSJSONSerialization dataWithJSONObject:putParams options:0 error:nil];
[request setHTTPBody:putData];

//部首:

[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [putData length]] forHTTPHeaderField:@"Content-Length"];

答案 1 :(得分:0)

我不见了

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

根据我的要求。之后我可以这样写我的请求:

let urlPath = "http://keebintest-pagh.rhcloud.com/login"
        let url = NSURL(string: urlPath)
        let session = URLSession.shared
        let request = NSMutableURLRequest(url: url as! URL)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "POST"



        let jsonObject: [String: Any] = [
            "email": email,
            "password": password,


            ]