Created
October 26, 2018 14:07
-
-
Save varantes/879257a96391bbf24e4b3aca36693f65 to your computer and use it in GitHub Desktop.
Inicializando o OkHttp3 com o JWT dos projetos Certibio
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package br.com.certibio.datavalid.web | |
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper | |
import okhttp3.OkHttpClient | |
import okhttp3.Request | |
import okhttp3.RequestBody | |
import okhttp3.logging.HttpLoggingInterceptor | |
import org.junit.BeforeClass | |
import org.slf4j.LoggerFactory | |
import org.springframework.http.HttpHeaders | |
import org.springframework.http.MediaType | |
class ControllerTest { | |
companion object { | |
private val log = LoggerFactory.getLogger(ControllerTest::class.java) | |
private const val domain_local = "http://localhost:8090" | |
private const val domain = domain_local | |
private const val TEMER = "fotos/temer.jpg" | |
private const val PHOTO = TEMER | |
private const val LOG_MARKER = "*************************************************************************************" | |
private val mapper = jacksonObjectMapper().findAndRegisterModules()!! | |
private val logOkHttp = (System.getProperty("logOkHttp") == "true") | |
private const val login = "user" | |
private const val password = "password" | |
private lateinit var okHttpClient: OkHttpClient | |
private lateinit var jwt: String | |
private lateinit var httpHeaders: HttpHeaders | |
@JvmStatic | |
@BeforeClass | |
fun setUpClass() { | |
okHttpClient = OkHttpClient.Builder().apply { | |
if (logOkHttp) { | |
addInterceptor(HttpLoggingInterceptor() | |
.setLevel(HttpLoggingInterceptor.Level.BODY)) | |
} | |
}.build() | |
val bodyAsJson = mapper.writeValueAsString(mapOf("username" to login, "password" to password)) | |
val requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json"), bodyAsJson) | |
val loginRequest = Request.Builder().post(requestBody).url("$domain/login").build() | |
okHttpClient.newCall(loginRequest).execute().use { response -> | |
jwt = response.body()?.string() ?: throw ExceptionInInitializerError("Erro ao obter JWT do Facecheck") | |
log.info("jwt = $jwt") | |
} | |
httpHeaders = HttpHeaders().apply { | |
contentType = MediaType.APPLICATION_JSON | |
set("Authorization", "Bearer $jwt") | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment