Best Fuel code snippet using com.github.kittinunf.fuel.core.requests.DefaultBody.asString
DefaultRequest.kt
Source:DefaultRequest.kt
...390 * @return [String] the string representation391 */392 override fun toString(): String = buildString {393 appendln("--> $method $url")394 appendln("Body : ${body.asString(header(Headers.CONTENT_TYPE).lastOrNull())}")395 appendln("Headers : (${headers.size})")396 val appendHeaderWithValue = { key: String, value: String -> appendln("$key : $value") }397 headers.transformIterate(appendHeaderWithValue)398 }399 override fun response(handler: ResponseResultHandler<ByteArray>) =400 response(ByteArrayDeserializer(), handler)401 override fun response(handler: ResultHandler<ByteArray>) =402 response(ByteArrayDeserializer(), handler)403 override fun response(handler: ResponseHandler<ByteArray>) =404 response(ByteArrayDeserializer(), handler)405 override fun response(handler: Handler<ByteArray>) =406 response(ByteArrayDeserializer(), handler)407 override fun response() =408 response(ByteArrayDeserializer())...
BodyRepresentationTest.kt
Source:BodyRepresentationTest.kt
...13 private val manager: FuelManager by lazy { FuelManager() }14 @Test15 fun emptyBodyRepresentation() {16 assertThat(17 DefaultBody.from({ ByteArrayInputStream(ByteArray(0)) }, { 0L }).asString("(unknown)"),18 equalTo("(empty)")19 )20 }21 @Test22 fun unknownBytesRepresentation() {23 val bytes = ByteArray(555 - 16)24 .also { Random().nextBytes(it) }25 .let { ByteArray(16).plus(it) }26 mock.chain(27 request = mock.request().withMethod(Method.GET.value).withPath("/bytes"),28 response = mock.response().withBody(BinaryBody(bytes, null)).withHeader("Content-Type", "")29 )30 val (_, response, _) = manager.request(Method.GET, mock.path("bytes")).responseString()31 assertThat(32 response.body().asString(response[Headers.CONTENT_TYPE].lastOrNull()),33 equalTo("(555 bytes of (unknown))")34 )35 }36 @Test37 fun guessContentType() {38 val decodedImage = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVQYV2NgYAAAAAMAAWgmWQ0AAAAASUVORK5CYII=".decodeBase64()!!39 assertThat(40 DefaultBody41 .from({ ByteArrayInputStream(decodedImage) }, { decodedImage.size.toLong() })42 .asString(URLConnection.guessContentTypeFromStream(ByteArrayInputStream(decodedImage))),43 equalTo("(${decodedImage.size} bytes of image/png)")44 )45 }46 @Test47 fun bytesRepresentationOfOctetStream() {48 val contentTypes = listOf("application/octet-stream")49 val content = ByteArray(555 - 16)50 .also { Random().nextBytes(it) }51 .let { ByteArray(16).plus(it) }52 contentTypes.forEach { contentType ->53 assertThat(54 DefaultBody55 .from({ ByteArrayInputStream(content) }, { content.size.toLong() })56 .asString(contentType),57 equalTo("(555 bytes of $contentType)")58 )59 }60 }61 @Test62 fun bytesRepresentationOfMedia() {63 val contentTypes = listOf(64 "image/bmp", "image/gif", "image/jpeg", "image/png", "image/tiff", "image/webp", "image/x-icon",65 "audio/aac", "audio/midi", "audio/x-midi", "audio/ogg", "audio/wav", "audio/webm", "audio/3gpp", "audio/3gpp2",66 "video/mpeg", "video/ogg", "video/webm", "video/x-msvideo", "video/3gpp", "video/3gpp2",67 "font/otf", "font/ttf", "font/woff", "font/woff2"68 )69 val content = ByteArray(555 - 16)70 .also { Random().nextBytes(it) }71 .let { ByteArray(16).plus(it) }72 contentTypes.forEach { contentType ->73 assertThat(74 DefaultBody75 .from({ ByteArrayInputStream(content) }, { content.size.toLong() })76 .asString(contentType),77 equalTo("(555 bytes of $contentType)")78 )79 }80 }81 @Test82 fun textRepresentationOfYaml() {83 val contentTypes = listOf("application/x-yaml", "text/yaml")84 val content = "language: c\n"85 contentTypes.forEach { contentType ->86 assertThat(87 DefaultBody88 .from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() })89 .asString(contentType),90 equalTo(content)91 )92 }93 }94 @Test95 fun textRepresentationOfXml() {96 val contentTypes = listOf("application/xml", "application/xhtml+xml", "application/vnd.fuel.test+xml", "image/svg+xml")97 val content = "<html xmlns=\"http://www.w3.org/1999/xhtml\"/>"98 contentTypes.forEach { contentType ->99 assertThat(100 DefaultBody101 .from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() })102 .asString(contentType),103 equalTo(content)104 )105 }106 }107 @Test108 fun textRepresentationOfScripts() {109 val contentTypes = listOf("application/javascript", "application/typescript", "application/vnd.coffeescript")110 val content = "function test()"111 contentTypes.forEach { contentType ->112 assertThat(113 DefaultBody114 .from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() })115 .asString(contentType),116 equalTo(content)117 )118 }119 }120 @Test121 fun textRepresentationOfJson() {122 val contentTypes = listOf("application/json")123 val content = "{ \"foo\": 42 }"124 contentTypes.forEach { contentType ->125 assertThat(126 DefaultBody127 .from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() })128 .asString(contentType),129 equalTo(content)130 )131 }132 }133 @Test134 fun textRepresentationOfJsonWithUtf8Charset() {135 val contentTypes = listOf("application/json;charset=utf-8", "application/json; charset=utf-8")136 val content = "{ \"foo\": 42 }"137 contentTypes.forEach { contentType ->138 assertThat(139 DefaultBody140 .from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() })141 .asString(contentType),142 equalTo(content)143 )144 }145 }146 @Test147 fun textRepresentationOfJsonWithUtf8AndOtherParameters() {148 val contentTypes = listOf(149 "application/json;charset=utf-8;api-version=5.1",150 "application/json; charset=utf-8; api-version=5.1",151 "application/json;api-version=5.1;charset=utf-8",152 "application/json; api-version=5.1; charset=utf-8",153 "application/json;test=true;charset=utf-8;api-version=5.1",154 "application/json; test=true; charset=utf-8; api-version=5.1"155 )156 val content = "{ \"foo\": 42 }"157 contentTypes.forEach { contentType ->158 assertThat(159 DefaultBody160 .from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() })161 .asString(contentType),162 equalTo(content)163 )164 }165 }166 @Test167 fun textRepresentationOfJsonWithDifferentCharsets() {168 val contentString = "{ \"foo\": 42 }"169 val contentMap = mapOf(170 "application/json; charset=utf-8" to Charsets.UTF_8,171 "application/json; charset=utf-16" to Charsets.UTF_16,172 "application/json; charset=utf-32" to Charsets.UTF_32,173 "application/json; charset=iso-8859-1" to Charsets.ISO_8859_1,174 "application/json; charset=ascii" to Charsets.US_ASCII175 )176 contentMap.forEach { (contentType, charset) ->177 assertThat(178 DefaultBody179 .from({ ByteArrayInputStream(contentString.toByteArray(charset)) }, { contentString.length.toLong() })180 .asString(contentType),181 equalTo(contentString)182 )183 }184 }185 @Test186 fun textRepresentationOfJsonWithoutCharset() {187 val contentTypes = listOf(188 "application/json;api-version=5.1",189 "application/json; api-version=5.1"190 )191 val content = "{ \"foo\": 42 }"192 contentTypes.forEach { contentType ->193 assertThat(194 DefaultBody195 .from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() })196 .asString(contentType),197 equalTo(content)198 )199 }200 }201 @Test202 fun textRepresentationOfCsv() {203 val contentTypes = listOf("text/csv")204 val content = "function test()"205 contentTypes.forEach { contentType ->206 assertThat(207 DefaultBody208 .from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() })209 .asString(contentType),210 equalTo(content)211 )212 }213 }214 @Test215 fun textRepresentationOfCsvWithUtf16beCharset() {216 val contentTypes = listOf("application/csv; charset=utf-16be", "application/csv;charset=utf-16be")217 val content = String("hello,world!".toByteArray(Charsets.UTF_16BE))218 contentTypes.forEach { contentType ->219 assertThat(220 DefaultBody221 .from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() })222 .asString(contentType),223 equalTo("hello,world!")224 )225 }226 }227 @Test228 fun textRepresentationOfTextTypes() {229 val contentTypes = listOf("text/csv", "text/html", "text/calendar", "text/plain", "text/css")230 val content = "maybe invalid but we don't care"231 contentTypes.forEach { contentType ->232 assertThat(233 DefaultBody234 .from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() })235 .asString(contentType),236 equalTo(content)237 )238 }239 }240}...
UploadBody.kt
Source:UploadBody.kt
...26 * Represents this body as a string27 * @param contentType [String] the type of the content in the body, or null if a guess is necessary28 * @return [String] the body as a string or a string that represents the body such as (empty) or (consumed)29 */30 override fun asString(contentType: String?) = representationOfBytes("multipart/form-data")31 /**32 * Returns if the body is consumed.33 * @return [Boolean] if true, `writeTo`, `toStream` and `toByteArray` may throw34 */35 override fun isConsumed() = !inputAvailable36 /**37 * Returns the body emptiness.38 * @return [Boolean] if true, this body is empty39 */40 override fun isEmpty() = false41 /**42 * Returns the body as an [InputStream].43 *44 * @note callers are responsible for closing the returned stream....
FuelExtensionsTest.kt
Source:FuelExtensionsTest.kt
...94 )95 FuelManager.instance.client = client96 val (_, response, _) = Fuel.get("https://example.com").responseStringWithRetries(1)97 assertEquals(400, response.statusCode)98 assertEquals("unhandled error", response.body().asString("text/html"))99 }100 @Test101 fun `responseStringWithRetries returns fallback error handler's response when faced with a non-throttled error response`() {102 val client = mock<Client>()103 `when`(client.executeRequest(any())).thenReturn(104 Response(105 statusCode = 400,106 url = URL("https://example.com"),107 body = DefaultBody.from({ ByteArrayInputStream("unhandled error".toByteArray()) }, null)108 )109 )110 FuelManager.instance.client = client111 val (_, response, _) = Fuel.get("https://example.com").responseStringWithRetries(1) { r, _ ->112 ResponseResultOf(113 r.first,114 Response(115 statusCode = 400,116 url = URL("https://example.com"),117 body = DefaultBody.from({ ByteArrayInputStream("handled error".toByteArray()) }, null)118 ),119 r.third120 )121 }122 assertEquals(400, response.statusCode)123 assertEquals("handled error", response.body().asString("text/html"))124 }125 private fun createRetryResponse(126 retryAfter: String,127 headers: Headers = Headers.from(Headers.RETRY_AFTER to listOf(retryAfter))128 ) = Response(129 statusCode = 429,130 responseMessage = "RETRY",131 url = URL("https://example.com"),132 headers = headers133 )134}...
DefaultBody.kt
Source:DefaultBody.kt
...19 * Represents this body as a string20 * @param contentType [String] the type of the content in the body, or null if a guess is necessary21 * @return [String] the body as a string or a string that represents the body such as (empty) or (consumed)22 */23 override fun asString(contentType: String?): String {24 return when {25 isEmpty() -> "(empty)"26 isConsumed() -> "(consumed)"27 else -> representationOfBytes(contentType ?: URLConnection.guessContentTypeFromStream(openStream()))28 }29 }30 /**31 * Returns the body as a [ByteArray].32 *33 * @note Because the body needs to be read into memory anyway, implementations may choose to make the [Body]34 * readable once more after calling this method, with the original [InputStream] being closed (and release its35 * resources). This also means that if an implementation choose to keep it around, `isConsumed` returns false.36 *37 * @return the entire body...
RepeatableBody.kt
Source:RepeatableBody.kt
...60 * Represents this body as a string61 * @param contentType [String] the type of the content in the body, or null if a guess is necessary62 * @return [String] the body as a string or a string that represents the body such as (empty) or (consumed)63 */64 override fun asString(contentType: String?) = body.asString(contentType)65 /**66 * Returns the length of the body in bytes67 * @return [Long?] the length in bytes, null if it is unknown68 */69 override val length = body.length70 /**71 * Makes the body repeatable by e.g. loading its contents into memory72 * @return [RepeatableBody] the body to be repeated73 */74 override fun asRepeatable(): RepeatableBody = this75}...
Response.kt
Source:Response.kt
...39 return buildString {40 appendln("<-- $statusCode $url")41 appendln("Response : $responseMessage")42 appendln("Length : $contentLength")43 appendln("Body : ${body.asString(headers[Headers.CONTENT_TYPE].lastOrNull())}")44 appendln("Headers : (${headers.size})")45 val appendHeaderWithValue = { key: String, value: String -> appendln("$key : $value") }46 headers.transformIterate(appendHeaderWithValue)47 }48 }49 companion object {50 fun error(url: URL = URL("http://.")): Response = Response(url)51 }52}53val Response.isStatusInformational54 get() = (statusCode / 100) == 155val Response.isSuccessful56 get() = (statusCode / 100) == 257val Response.isStatusRedirection...
asString
Using AI Code Generation
1val body = DefaultBody("Hello World")2println(body.asString())3val body = ByteArrayBody("Hello World".toByteArray())4println(body.asString())5val body = InputStreamBody("Hello World".byteInputStream())6println(body.asString())7val body = FileBody(File("/tmp/file.txt"))8println(body.asString())9val body = StreamBody("Hello World".byteInputStream())10println(body.asString())11val body = StreamBody("Hello World".byteInputStream())12println(body.asString())13val body = StreamBody("Hello World".byteInputStream())14println(body.asString())15val body = StreamBody("Hello World".byteInputStream())16println(body.asString())17val body = StreamBody("Hello World".byteInputStream())18println(body.asString())19val body = StreamBody("Hello World".byteInputStream())20println(body.asString())21val body = StreamBody("Hello World".byteInputStream())22println(body.asString())23val body = StreamBody("Hello World".byteInputStream())24println(body.asString())25val body = StreamBody("Hello World".byteInputStream())26println(body.asString())
asString
Using AI Code Generation
1val body = DefaultBody.fromString("body")2val body = DefaultBody.asByteArray("body".toByteArray())3val body = DefaultBody.asStream("body".byteInputStream())4val body = DefaultBody.asFile(File("file"))5val body = DefaultBody.asJson("body")6val body = DefaultBody.asJson("body")7val body = DefaultBody.asXml("body")8val body = DefaultBody.asXml("body")9val body = DefaultBody.asXml("body")10val body = DefaultBody.asXml("body")11val body = DefaultBody.asXml("body")12val body = DefaultBody.asXml("body")13val body = DefaultBody.asXml("body")14val body = DefaultBody.asXml("body")15val body = DefaultBody.asXml("body")
asString
Using AI Code Generation
1val body: RequestBody = RequestBody().asString("Hello World")2val body: RequestBody = RequestBody().asJson("{ \"hello\": \"world\" }")3val body: RequestBody = RequestBody().asByteArray(byteArrayOf(0x00, 0x01, 0x02, 0x03))4val body: RequestBody = RequestBody().asStream(FileInputStream("path/to/file"))5val body: RequestBody = RequestBody().asFile(File("path/to/file"))6val body: RequestBody = RequestBody().asChannel(ByteArray(10).toByteChannel())7val body: RequestBody = RequestBody().asChannel(ByteArray(10).toByteChannel(), 10)8val body: RequestBody = RequestBody().asChannel(ByteArray(10).toByteChannel(), 10, { })9val body: RequestBody = RequestBody().asChannel(ByteArray(10).toByteChannel(), 10, { }, { })10val body: RequestBody = RequestBody().asChannel(ByteArray(10).toByteChannel(), 10, { }, { }, { })11val body: RequestBody = RequestBody().asChannel(ByteArray(10).toByteChannel(), 10, { }, { }, { }, { })
asString
Using AI Code Generation
1if (body != null) {2val bodyAsString = body.asString()3}4if (body != null) {5val bodyAsString = body.asString()6}7if (body != null) {8val bodyAsString = body.asString()9}10if (body != null) {11val bodyAsString = body.asString()12}
asString
Using AI Code Generation
1val body = DefaultBody.fromString("Hello World")2val (request, response, result) = request.responseString()3val body = DefaultBody.asJson("""{"foo": "bar"}""")4val (request, response, result) = request.responseString()5val body = DefaultBody.asByteArray(byteArrayOf(0, 1, 2, 3))6val (request, response, result) = request.responseString()7val body = DefaultBody.asStream(ByteArrayInputStream(byteArrayOf(0, 1, 2, 3)))8val (request, response, result) = request.responseString()9val body = DefaultBody.asFile(File("/path/to/file"))10val (request, response, result) = request.responseString()11val body = DefaultBody.asChannel(ByteArrayInputStream(byteArrayOf(0, 1, 2, 3)).channel)12val (request, response, result) = request.responseString()13val body = DefaultBody.asChannel(ByteArrayInputStream(byteArrayOf(0, 1, 2, 3)).channel, 1024)14val (request, response, result) = request.responseString()
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!