简体   繁体   中英

How do I fetch HTML of URL using Vapor Swift?

In one of my routes, I want to fetch HTML from a different site. https://docs.vapor.codes/4.0/content/ documents support for JSON and such but I couldn't find anything on raw HTML.

request.client.get(URI(string: "https://example.com/")).map { (response: ClientResponse) -> String? in
    if response.status == .ok && response.content.contentType == .html {
        return response.content... // How do I get raw html?
    }

    return nil
}

How do I get the raw HTML from the client response?

There are a couple of ways you can do this, depending on which String initializer you happen to fancy. Note that to use any of the following methods, you will need to unwrap the response body first:

guard let body = response.body else {
    throw Abort(.internalServerError)
}

The first way is using the ByteBuffer.readString method.

guard let html = body.readString(length: body.readableBytes) else {
    throw Abort(.internalServerError)
}

Another way is to use the String(decoding:as:) initializer, which can be used to convert any collection of UInt8 integers to a String :

let html = String(decoding: body.readableBytesView, as: UTF8.self)

Anf finally, you can use the String(buffer:) initializer that @iMike suggested.

let html = String(buffer: body)

Keep in mind that the .readBytes method will increment the .readIndex of the ByteBuffer , while the String initializers won't. Though I imagine that this doesn't really matter in your case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM