Swift POST语句返回500状态代码

时间:2016-08-11 18:26:24

标签: ios swift rest

我试图对服务器进行调用,然后收到500状态代码。我已尝试发送序列化的json对象和带参数的编码字符串。我无法访问服务器,所以我不知道服务器是否存在问题,但GET和DELETE调用有效。 POST和PUT不要。这是代码:

    guard let urlComponents = NSURLComponents(string: url) else
    {
        print("error creating URL")
        return (nil, nil)
    }

    for (key, value) in urlParameters
    {
        urlComponents.queryItems = [NSURLQueryItem(name:key, value:value)]
    }

    let urlRequest = NSMutableURLRequest(URL: urlComponents.URL!)
    urlRequest.HTTPMethod = "POST"
    let config = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session = NSURLSession(configuration: config)

    do
    {
        let jsonUser = try NSJSONSerialization.dataWithJSONObject(["firstname": "Bob", "lastname": "Johnson", "summary": "Hi"], options: [])
        urlRequest.HTTPBody = jsonUser
    }
    catch
    {
        print("Error: cannot create JSON from user")
    }
    let task = session.dataTaskWithRequest(urlRequest)
    {
    (data, response, error) in
    ....

我也试过像这样设置httpbody:

    let postString = "firstname=Jack&lastname=Daniels&summary=hello"

    urlRequest.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

这是我得到的服务器响应:

response: <NSHTTPURLResponse: 0x7ff3137a3b70> { URL: https://somelink } { status code: 500, headers {
Connection = "keep-alive";
"Content-Length" = 1477;
"Content-Type" = "text/html; charset=utf-8";
Date = "Thu, 11 Aug 2016 00:42:52 GMT";
Server = "WEBrick/1.3.1 (Ruby/2.2.4/2015-12-16)";
Via = "1.1 vegur";
"X-Request-Id" = "4c414334-4412-48a4-a61f-c17658182bdf";
"X-Runtime" = "0.007021";
} }

这是我的POST请求还是服务器的问题?

2 个答案:

答案 0 :(得分:3)

似乎问题是响应没有按照服务器尝试读取它的方式进行格式化。因此,如果其他人有这个问题,请仔细检查您的服务器(在我的情况下,我必须通过电子邮件发送给某人并收到正确的格式)。

答案 1 :(得分:2)

500是内部服务器错误。没有办法从客户那里知道为什么它会返回。您需要与运行服务器的人交谈。

我唯一看到你可能有错的是:

for (key, value) in urlParameters
{
    urlComponents.queryItems = [NSURLQueryItem(name:key, value:value)]
}

应该是这样的:

urlComponents.queryItems = []
for (key, value) in urlParameters
{
    urlComponents.queryItems?.append(NSURLQueryItem(name:key, value:value))
}