How to use body method of com.github.kittinunf.fuel.core.requests.DefaultRequest class

Best Fuel code snippet using com.github.kittinunf.fuel.core.requests.DefaultRequest.body

ParameterEncoderTest.kt

Source:ParameterEncoderTest.kt Github

copy

Full Screen

...68 assertThat(request.url.toExternalForm(), not(containsString("?")))69 assertThat(request.url.query, not(containsString("foo=bar")))70 val contentType = request[Headers.CONTENT_TYPE].lastOrNull()?.split(';')?.first()71 assertThat(contentType, equalTo("application/x-www-form-urlencoded"))72 assertThat(request.body.asString(contentType), equalTo("foo=bar"))73 assertThat("Expected parameters to be cleared", request.parameters.isEmpty(), equalTo(true))74 executed = true75 request76 }(testRequest)77 assertThat("Expected encoder \"next\" to be called", executed, equalTo(true))78 }79 }80 @Test81 fun encodeRequestParametersInUrlWhenBodyExists() {82 val methods = listOf(Method.POST, Method.PATCH, Method.PUT)83 methods.forEach { method ->84 val testRequest = DefaultRequest(85 method,86 URL("https://test.fuel.com"),87 parameters = listOf("foo" to "bar")88 ).body("my current body")89 var executed = false90 ParameterEncoder { request ->91 assertThat(request.url.toExternalForm(), containsString("?"))92 assertThat(request.url.query, containsString("foo=bar"))93 val contentType = request[Headers.CONTENT_TYPE].lastOrNull()?.split(';')?.first()94 assertThat(contentType, equalTo("text/plain"))95 assertThat(request.body.asString(contentType), equalTo("my current body"))96 assertThat("Expected parameters to be cleared", request.parameters.isEmpty(), equalTo(true))97 executed = true98 request99 }(testRequest)100 assertThat("Expected encoder \"next\" to be called", executed, equalTo(true))101 }102 }103 @Test104 fun ignoreParameterEncodingForMultipartFormDataRequests() {105 val methods = listOf(Method.POST, Method.PATCH, Method.PUT)106 methods.forEach { method ->107 val testRequest = DefaultRequest(108 method,109 URL("https://test.fuel.com"),110 parameters = listOf("foo" to "bar")111 ).header(Headers.CONTENT_TYPE, "multipart/form-data")112 .upload()113 .add { BlobDataPart(ByteArrayInputStream("12345678".toByteArray()), name = "test", contentLength = 8L) }114 var executed = false115 ParameterEncoder { request ->116 assertThat(request.url.toExternalForm(), not(containsString("?")))117 assertThat(request.url.query, not(containsString("foo=bar")))118 val contentType = request[Headers.CONTENT_TYPE].lastOrNull()?.split(';')?.first()119 assertThat(contentType, equalTo("multipart/form-data"))120 val body = String(request.body.toByteArray())121 assertThat(body, containsString("foo"))122 assertThat(body, containsString("bar"))123 assertThat(body, containsString("test"))124 assertThat(body, containsString("12345678"))125 assertThat("Expected parameters not to be cleared", request.parameters.isEmpty(), equalTo(false))126 executed = true127 request128 }(testRequest)129 assertThat("Expected encoder \"next\" to be called", executed, equalTo(true))130 }131 }132 @Test133 fun encodeMultipleParameters() {134 val methods = listOf(Method.GET, Method.DELETE, Method.HEAD, Method.OPTIONS, Method.TRACE)135 methods.forEach { method ->136 val testRequest = DefaultRequest(137 method,138 URL("https://test.fuel.com"),...

Full Screen

Full Screen

FuelExtensionsTest.kt

Source:FuelExtensionsTest.kt Github

copy

Full Screen

...40 .thenReturn(41 Response(42 statusCode = 200,43 url = URL("https://example.com"),44 body = DefaultBody.from({ ByteArrayInputStream("final".toByteArray()) }, null)45 )46 )47 FuelManager.instance.client = client48 val (_, response, result) = Fuel.get("https://example.com")49 .responseStringWithRetries(1, 1L)50 assertEquals(200, response.statusCode)51 assertEquals("final", result.get())52 }53 @Test54 fun `responseStringWithRetries returns the last response when a non-throttle response is not received within retry count`() {55 val client = mock<Client>()56 `when`(client.executeRequest(any()))57 .thenReturn(basicRetryResponse)58 .thenReturn(basicRetryResponse)59 .thenReturn(basicRetryResponse) // One more than retry count60 .thenReturn(Response(statusCode = 200, url = URL("https://example.com")))61 FuelManager.instance.client = client62 val (_, response, result) = Fuel.get("https://example.com")63 .responseStringWithRetries(2, 1L) // Would have to be 3 to succeed64 assertEquals(429, response.statusCode) // Status code of last response65 assertTrue(result is Result.Failure)66 }67 @Test68 fun `responseStringWithRetries throws when an invalid Retry-After header is received`() {69 val client = mock<Client>()70 `when`(client.executeRequest(any())).thenReturn(createRetryResponse("INVALID VALUE"))71 FuelManager.instance.client = client72 assertThrows<NumberFormatException> {73 Fuel.get("https://example.com").responseStringWithRetries(1, 1L) // Would have to be 2 to succeed74 }75 }76 @Test77 fun `responseStringWithRetries throws when no Retry-After header is received in HTTP 429 response`() {78 val client = mock<Client>()79 `when`(client.executeRequest(any())).thenReturn(createRetryResponse("", Headers())) // No Retry-After header80 FuelManager.instance.client = client81 assertThrows<IllegalStateException> {82 Fuel.get("https://example.com").responseStringWithRetries(1)83 }84 }85 @Test86 fun `responseStringWithRetries returns non-throttled error by default`() {87 val client = mock<Client>()88 `when`(client.executeRequest(any())).thenReturn(89 Response(90 statusCode = 400,91 url = URL("https://example.com"),92 body = DefaultBody.from({ ByteArrayInputStream("unhandled error".toByteArray()) }, null)93 )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}...

Full Screen

Full Screen

BodyTest.kt

Source:BodyTest.kt Github

copy

Full Screen

...11import java.io.File12import java.net.URL13class BodyTest {14 @Test15 fun bodyIsEmptyByDefault() {16 val body = DefaultBody()17 assertThat(body.isEmpty(), equalTo(true))18 assertThat(body.isConsumed(), equalTo(false))19 val request = DefaultRequest(Method.POST, URL("https://test.fuel.com/"))20 assertThat(request.toString(), containsString("(empty)"))21 }22 @Test23 fun bodyIsConsumedAfterWriting() {24 val body = DefaultBody.from({ ByteArrayInputStream("body".toByteArray()) }, { 4 })25 assertThat(body.isConsumed(), equalTo(false))26 body.writeTo(ByteArrayOutputStream())27 assertThat(body.isConsumed(), equalTo(true))28 }29 @Test30 fun bodyFromString() {31 val value = "String Body ${Math.random()}"32 DefaultRequest(Method.POST, URL("https://test.fuel.com/"))33 .body(value)34 .apply {35 val output = ByteArrayOutputStream(value.length)36 assertThat(body.length?.toInt(), equalTo(value.length))37 assertThat(body.toByteArray(), equalTo(value.toByteArray()))38 body.writeTo(output)39 assertThat(output.toString(), equalTo(value))40 }41 }42 @Test43 fun bodyFromByteArray() {44 val value = ByteArray(32).apply {45 for (i in 0..(this.size - 1)) {46 this[i] = ('A'..'z').random().toByte()47 }48 }49 DefaultRequest(Method.POST, URL("https://test.fuel.com/"))50 .body(value)51 .apply {52 val output = ByteArrayOutputStream(value.size)53 assertThat(body.length?.toInt(), equalTo(value.size))54 assertArrayEquals(value, body.toByteArray())55 body.writeTo(output)56 assertArrayEquals(value, output.toByteArray())57 }58 }59 @Test60 fun bodyFromFile() {61 val value = "String Body ${Math.random()}"62 val file = File.createTempFile("BodyTest", ".txt")63 file.writeText(value)64 DefaultRequest(Method.POST, URL("https://test.fuel.com/"))65 .body(file)66 .apply {67 val output = ByteArrayOutputStream(value.length)68 assertThat(body.length?.toInt(), equalTo(value.length))69 assertThat(body.toByteArray(), equalTo(value.toByteArray()))70 body.writeTo(output)71 assertThat(output.toString(), equalTo(value))72 }73 }74 @Test75 fun bodyFromStream() {76 val value = "String Body ${Math.random()}"77 val stream = ByteArrayInputStream(value.toByteArray())78 DefaultRequest(Method.POST, URL("https://test.fuel.com/"))79 .body(stream)80 .apply {81 val output = ByteArrayOutputStream(value.length)82 assertThat(body.toByteArray(), equalTo(value.toByteArray()))83 body.writeTo(output)84 assertThat(output.toString(), equalTo(value))85 }86 }87 @Test(expected = FuelError::class)88 fun bodyFromCallbackCanOnlyBeReadOnce() {89 val body = DefaultBody.from({ ByteArrayInputStream("body".toByteArray()) }, { 4 })90 body.writeTo(ByteArrayOutputStream())91 body.writeTo(ByteArrayOutputStream())92 }93 @Test94 fun bodyToByteArrayLoadsItIntoMemory() {95 val value = "String Body ${Math.random()}"96 val body = DefaultBody.from({ ByteArrayInputStream(value.toByteArray()) }, { value.length.toLong() })97 body.toByteArray()98 val output = ByteArrayOutputStream(value.length)99 body.writeTo(output)100 assertThat(output.toString(), equalTo(value))101 }102 @Test103 fun requestWithBodyIsPrintableAfterConsumption() {104 val value = { ByteArrayInputStream("String Body ${Math.random()}".toByteArray()) }105 DefaultRequest(Method.POST, URL("https://test.fuel.com/"))106 .body(value)107 .apply {108 val output = ByteArrayOutputStream()109 body.writeTo(output)110 assertThat(this.toString(), containsString("(consumed)"))111 }112 }113}...

Full Screen

Full Screen

RepeatableBodyTest.kt

Source:RepeatableBodyTest.kt Github

copy

Full Screen

...9import java.net.URL10class RepeatableBodyTest {11 @Test12 fun repeatableBodyIsNeverConsumed() {13 val body = DefaultBody.from({ ByteArrayInputStream("body".toByteArray()) }, { 4 }).asRepeatable()14 assertThat(body.isConsumed(), equalTo(false))15 body.writeTo(ByteArrayOutputStream())16 assertThat(body.isConsumed(), equalTo(false))17 }18 @Test19 fun byteArrayBodyIsRepeatable() {20 val value = ByteArray(32).apply {21 for (i in 0..(this.size - 1)) {22 this[i] = ('A'..'z').random().toByte()23 }24 }25 DefaultRequest(Method.POST, URL("https://test.fuel.com/"))26 .body(value)27 .apply {28 val output = ByteArrayOutputStream(value.size)29 assertThat(body.length?.toInt(), equalTo(value.size))30 assertThat(body.toByteArray(), equalTo(value))31 body.writeTo(output)32 assertThat(output.toString(), equalTo(String(value)))33 assertThat(body.isConsumed(), equalTo(false))34 }35 }36 @Test37 fun stringBodyIsRepeatable() {38 val value = "body"39 DefaultRequest(Method.POST, URL("https://test.fuel.com/"))40 .body(value)41 .apply {42 val output = ByteArrayOutputStream(value.length)43 assertThat(body.length?.toInt(), equalTo(value.length))44 assertThat(body.toByteArray(), equalTo(value.toByteArray()))45 body.writeTo(output)46 assertThat(output.toString(), equalTo(value))47 assertThat(body.isConsumed(), equalTo(false))48 }49 }50 @Test51 fun requestWithRepeatableBodyIsPrintableAfterConsumption() {52 val value = "String Body ${Math.random()}"53 DefaultRequest(Method.POST, URL("https://test.fuel.com/"))54 .body(value)55 .apply {56 val output = ByteArrayOutputStream()57 body.writeTo(output)58 assertThat(this.toString(), CoreMatchers.containsString(value))59 }60 }61}...

Full Screen

Full Screen

FormattingTest.kt

Source:FormattingTest.kt Github

copy

Full Screen

...43 Method.POST,44 url = URL("http://httpbin.org/post"),45 headers = Headers.from("Content-Type" to "text/html"),46 parameters = listOf("foo" to "xxx")47 ).body("it's a body")48 MatcherAssert.assertThat(request.httpString(), CoreMatchers.startsWith("POST http"))49 MatcherAssert.assertThat(request.httpString(), CoreMatchers.containsString("Content-Type"))50 MatcherAssert.assertThat(request.httpString(), CoreMatchers.containsString("body"))51 }52}...

Full Screen

Full Screen

ObjectBodyTest.kt

Source:ObjectBodyTest.kt Github

copy

Full Screen

...14class ObjectBodyTest {15 @Test16 fun setsBodyCorrectly() {17 val expectedBody = "{\"foo\":42,\"bar\":\"foo bar\",\"fooBar\":\"foo bar\"}"18 val bodyObject = FakeObject()19 val request = DefaultRequest(Method.POST, URL("https://test.fuel.com/body"))20 .objectBody(bodyObject)21 assertThat(expectedBody, equalTo(String(request.body.toByteArray())))22 }23 @Test24 fun setsContentTypeCorrectly() {25 val bodyObject = listOf(26 42,27 mapOf("foo" to "bar")28 )29 val request = DefaultRequest(Method.POST, URL("https://test.fuel.com/body"))30 .objectBody(bodyObject)31 assertThat(request[Headers.CONTENT_TYPE].lastOrNull(), equalTo("application/json"))32 }33 @Test34 fun setsBodyCorrectlyWithCustomMapper() {35 val mapper = createCustomMapper()36 val expectedBody = "{\"foo\":42,\"bar\":\"foo bar\",\"foo_bar\":\"foo bar\"}"37 val bodyObject = FakeObject()38 val request = DefaultRequest(Method.POST, URL("https://test.fuel.com/body"))39 .objectBody(bodyObject, mapper = mapper)40 assertThat(expectedBody, equalTo(String(request.body.toByteArray())))41 }42 private fun createCustomMapper(): ObjectMapper {43 val mapper = ObjectMapper().registerKotlinModule()44 .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)45 mapper.propertyNamingStrategy = PropertyNamingStrategy.SNAKE_CASE46 return mapper47 }48}49data class FakeObject(50 val foo: Int = 42,51 val bar: String = "foo bar",52 val fooBar: String = "foo bar"53)...

Full Screen

Full Screen

DefaultRequestTest.kt

Source:DefaultRequestTest.kt Github

copy

Full Screen

...12 Method.POST,13 url = URL("http://httpbin.org/post"),14 headers = Headers.from("Content-Type" to "text/html"),15 parameters = listOf("foo" to "xxx")16 ).body("it's a body")17 val printed = request.toString()18 assertThat(printed, containsString("-->"))19 assertThat(printed, containsString("POST"))20 assertThat(printed, containsString("http://httpbin.org/post"))21 assertThat(printed, containsString("it's a body"))22 assertThat(printed, containsString("Content-Type"))23 assertThat(printed, containsString("text/html"))24 }25}...

Full Screen

Full Screen

JsonBodyTest.kt

Source:JsonBodyTest.kt Github

copy

Full Screen

...8import java.net.URL9class JsonBodyTest {10 @Test11 fun setsBodyCorrectly() {12 val body = "[42, { \"foo\": \"bar\" }]"13 val request = DefaultRequest(Method.POST, URL("https://test.fuel.com/body"))14 .jsonBody(body)15 assertThat(body, equalTo(String(request.body.toByteArray())))16 }17 @Test18 fun setsContentTypeCorrectly() {19 val request = DefaultRequest(Method.POST, URL("https://test.fuel.com/body"))20 .jsonBody("[42, { \"foo\": \"bar\" }]")21 assertThat(request[Headers.CONTENT_TYPE].lastOrNull(), equalTo("application/json"))22 }23}...

Full Screen

Full Screen

body

Using AI Code Generation

copy

Full Screen

1 .header("Content-Type" to "application/json")2 .body("{\"key\":\"value\"}")3 .response()4 .response()5 .body("{\"key\":\"value\"}")6 .response()7 .body("{\"key\":\"value\"}".toByteArray())8 .response()9 .body("{\"key\":\"value\"}".toByteArray(), "application/json")10 .response()11 .body("{\"key\":\"value\"}".toByteArray(), "application/json")12 .header("Content-Type" to "application/json")13 .response()14 .body("{\"key\":\"value\"}".toByteArray(), "application/json")15 .header("Content-Type" to "application/json")16 .body("{\"

Full Screen

Full Screen

body

Using AI Code Generation

copy

Full Screen

1val (request, response, result) = Fuel.post(url, listOf("name" to "John Doe")).body("Hello World").responseString()2val (request, response, result) = Fuel.post(url, listOf("name" to "John Doe")).header("Content-Type" to "application/json").responseString()3val (request, response, result) = Fuel.post(url, listOf("name" to "John Doe")).timeout(10000).responseString()4val (request, response, result) = Fuel.post(url, listOf("name" to "John Doe")).timeoutRead(10000).responseString()5val (request, response, result) = Fuel.post(url, listOf("name" to "John Doe")).timeoutWrite(10000).responseString()6val (request, response, result) = Fuel.post(url, listOf("name" to "John Doe")).followRedirects(true).responseString()7val (request, response, result) = Fuel.post(url, listOf("name" to "John Doe")).userAgent("My User Agent").responseString()8val (request, response, result) = Fuel.post(url, listOf("name" to "John Doe")).progress { readBytes, totalBytes -> println("Progress: $readBytes / $totalBytes") }.responseString()9val (request, response, result) = Fuel.post(url, listOf("name" to "John Doe")).response { request, response, result -> println("Response: $response") }

Full Screen

Full Screen

body

Using AI Code Generation

copy

Full Screen

1 .body("{\"foo\": \"bar\"}")2 .responseString { request, response, result ->3 println(request)4 println(response)5 println(result)6 }7 .jsonBody("{\"foo\": \"bar\"}")8 .responseString { request, response, result ->9 println(request)10 println(response)11 println(result)12 }13repositories {14 mavenCentral()15}16dependencies {17}18The MIT License (MIT)19Copyright (C) 2013-2016 Kittinun Vantasin20of this software and associated documentation files (the "Software"), to deal

Full Screen

Full Screen

body

Using AI Code Generation

copy

Full Screen

1fun getResponse(url: String): String{2 Fuel.get(url).body { request, response, result ->3 val (bytes, error) = result4 if (bytes != null) {5 response = String(bytes)6 }7 }8}9fun main(args: Array<String>) {10 val response = getResponse(url)11 println(response)12}

Full Screen

Full Screen

body

Using AI Code Generation

copy

Full Screen

1val request = Fuel.post("/posts")2 .body("title=foo&body=bar&userId=1")3 .response { request, response, result ->4 println(request.body())5 }6val request = Fuel.get("/posts")7 .response { request, response, result ->8 println(request)9 }10request.cancel()11val request = Fuel.get("/posts")12 .timeout(2000)13 .response { request, response, result ->14 println(request)15 }16val request = Fuel.get("/posts")17 .redirects(5)18 .response { request, response, result ->19 println(request)20 }21val request = Fuel.get("/posts")22 .response { request, response, result ->23 println(response)24 }25val request = Fuel.get("/posts")26 .response { request, response, result ->27 println(response.headers)28 }29val request = Fuel.get("/posts")30 .response { request, response, result ->31 println(response.headers)32 }33val request = Fuel.get("/posts")34 .response { request, response, result ->35 println(response.body())36 }

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Fuel automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful