加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

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

发布时间:2020-12-14 02:21:50 所属栏目:Linux 来源:网络整理
导读:我们想要发出HTTP(S)请求(GET)来调用API.问题是,NSURLRequest(目前)尚未在 Linux for Foundation( https://github.com/apple/swift-corelibs-foundation/blob/master/Foundation/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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读