linux – 没有NSURLRequest的Swift中的HTTP请求

前端之家收集整理的这篇文章主要介绍了linux – 没有NSURLRequest的Swift中的HTTP请求前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我们想要发出HTTP(S)请求(GET)来调用API.问题是,NSURLRequest(目前)尚未在 Linux for Foundation( https://github.com/apple/swift-corelibs-foundation/blob/master/Foundation/NSURLRequest.swift)中实现.

是否还有其他创建HTTP请求的可能性?

解决方法

有一个名为HTTPMiddleware的好项目可能很有用,它只是一个中间件框架,但效果很好.

这是一个代码示例:

import HTTP
import HTTPMiddleware

struct Middleware: HTTPRequestMiddlewareType {
    func respond(request: HTTPRequest) -> HTTPRequestMiddlewareResult {
        // You can change the request and pass it forward
        return .Next(request)

        // Or you can respond early and bypass the chain
        return .Respond(HTTPResponse(statusCode: 404,reasonPhrase: "Not Found"))
    }
}

struct Responder: HTTPResponderType {
    func respond(request: HTTPRequest) -> HTTPResponse {
        // May or may not be called depending on the middleware
        return HTTPResponse(statusCode: 200,reasonPhrase: "OK")
    }
}

let request = HTTPRequest(method: .GET,uri: URI(path: "/"))
let chain = Middleware() >>> Responder()
let response = chain.respond(request)

这是官方的page,你也可以在源代码中找到一个对常见请求有用的JSON解析器.安装只需要uri_parser.

猜你在找的Linux相关文章