boxi boxi - 7 months ago 152
Linux Question

HTTP Request in Swift without NSURLRequest

we want to make a http(s) requests (GET) to call an api. The Problem is, NSURLRequest is (at the moment) not implemented in the Foundation for Linux (
Are there any other possibilities to create a HTTP-request?


There is a nice project called HTTPMiddleware that can be useful, it's just a middleware framework but it work well.

Some code example:

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)

Here there is the official page, you can find also a JSON parser in the sources that can be useful for the common requests. The installation require only uri_parser.