使用swift获取HTTP状态 [英] Get HTTP Status using swift

查看:138
本文介绍了使用swift获取HTTP状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,我没有找到问题的答案(((请不要太苛刻,我不是专业的程序员,但是我一直在学习,希望一旦我能够回答某人的问题, ))

I am sorry, I haven't found an answer for my question(( Please, don't be very harsh, I am not a professional programmer, but I keep learning and hope once I will be able to answer someone's question))

我正在尝试获取链接的HTTP状态(我是根据一个数据库条目代码(例如ABCDEF)生成链接,我将它们保留在数组中,然后生成到第二个数据库(例如www.blablabla)的链接. ABCDEF.net),这样我就可以查看该页面是否存在于数据库中.

I am trying to get HTTP Status of the link (I am sort of generating links depending on one database entries code, like ABCDEF, I keep them in an array and then generate a link to second database, like www.blablabla.ABCDEF.net), so I can see whether the page exists in database or not.

我已经编写了这段代码,但是出了点问题.所以也许是这样的问题:我的代码有什么问题?"但是他们在栈上还说,您必须展示解决问题的尝试...

I have written this code, but something is wrong. So maybe it's a question like: "What's wrong with my code?" But on the stack they also say, you have to show your attempts of problem solving...

我希望我能保持所有组件的快速运行,而无需任何其他模块或东西,我认为NSHTTPURLResponse足够了,但是我以某种方式使用了它.

I wish I could keep it all swift, without any additional modules or something, I think NSHTTPURLResponse must be enough, but I am using it somehow wrong.

期待帮助和答复))

var err: NSError!

NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData!, error: err) -> Void in

    if (err != nil) {
        let httpStatus: NSHTTPURLResponse = response as NSHHTPURLResponse
        for myLink in allLinks {
            println("HERE IS THE CURRENT STATUS CODE" + httpStatus.statusCode + "OF A LINK:" + myLink)
            if httpStatus.statusCode == 200 {println("SUCCESS!!!!!")}
        }
    }
}

推荐答案

此处的基本问题是,仅当err不是nil时,您才在看statusCode.但是,如果有错误,则可能没有状态码.闭包的错误参数表示基本的网络问题,它可能阻止您进入有问题的页面. statusCode通常仅在出现错误 (即您成功连接到服务器)时才有意义,在这种情况下,statusCode是服务器如何通知您的能力服务HTTP请求.

The fundamental issue here is that you appear to be looking at the statusCode only if the err is not nil. But if you have error, you probably don't have status code. The error parameter to the closure indicates fundamental network issue that probably prevented you from getting to the page in question. The statusCode is generally only meaningful if the error was nil (i.e. you succeeded in connecting to the server), in which case the statusCode is how the server informs you of its ability to service the HTTP request.

一些小事:

  1. 您不需要var err: NSError!行(因为error对象作为参数传递给闭包).您已声明的变量在这里不使用.

  1. You don't need the var err: NSError! line (because the error object is passed as parameter to the closure). This variable you've declared is not used here.

我不知道error: err作为闭包的第三个参数如何工作.语法为"variableName:variableType",但没有err类型.

I don't see how error: err as the third parameter to the closure could have worked. The syntax is "variableName: variableType", but there is no type of err.

同样,您的代码引用的是不存在的类NSHHTPURLResponse.在Swift 3和更高版本中,它是HTTPURLResponse.

Likewise, your code is referring to a non-existent class, NSHHTPURLResponse. In Swift 3 and later, it's HTTPURLResponse.

为获取statusCode而对HTTPURLResponse进行检索时,最好执行if let.

It's probably prudent to do if let for the retrieval of the HTTPURLResponse in order to get the statusCode.

我不清楚您打算遍历allLinks的意图,因为此连接仅用于给定的request,而不是一堆链接.只需根据特定的request来查看statusCode.如果需要测试多个URL,则对每个URL单独进行request.

I'm unclear as to your intent in iterating through allLinks, because this connection is just for a given request, not a bunch of links. Just look at the statusCode in light of the particular request. If you need to test multiple URLs, then you do a separate request for each.

我们应该将200到299之间的任何代码视为成功,而不仅仅是200.我建议使用范围200 ..< 300.

We should consider any codes between 200 and 299 as success, not just 200. I'd suggest using the range 200 ..< 300.

因此:

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, let httpResponse = response as? HTTPURLResponse, error == nil else {
        print("No valid response")
        return
    }

    guard 200 ..< 300 ~= httpResponse.statusCode else {
        print("Status code was \(httpResponse.statusCode), but expected 2xx")
        return
    }

    // everything OK, process `data` here
}
task.resume()

我还做了其他一些更改(针对Swift 3和更高版本进行了更新;使用URLSession而不是URLConnection;我认为error是变量名的不错选择;我更喜欢尾随闭包语法;我倾向于使用推断类型作为闭包参数以使声明更简洁等),但这对手头的问题无关紧要:希望这说明了如何检查状态码.

I also made a few other changes (updated for Swift 3 and later; use URLSession rather than URLConnection; I think error is fine choice for the variable name; I prefer the trailing closure syntax; I tend to use inferred types for closure parameters to make the declaration a little more concise, etc.), but all of that is immaterial to the question at hand: Hopefully this illustrates how one checks the status code.

有关Swift 2再现,请参见此答案的先前版本.

For Swift 2 rendition, see previous revision of this answer.

这篇关于使用swift获取HTTP状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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