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.

相关文章

文章浏览阅读1.8k次,点赞63次,收藏54次。Linux下的目录权限...
文章浏览阅读1.6k次,点赞44次,收藏38次。关于Qt的安装、Wi...
本文介绍了使用shell脚本编写一个 Hello
文章浏览阅读1.5k次,点赞37次,收藏43次。【Linux】初识Lin...
文章浏览阅读3k次,点赞34次,收藏156次。Linux超详细笔记,...
文章浏览阅读6.8k次,点赞109次,收藏114次。【Linux】 Open...