mirror of
https://github.com/corda/corda.git
synced 2024-12-23 14:52:29 +00:00
Added new test utilities for HTTP requests.
This commit is contained in:
parent
39cbab9ce1
commit
7eeea97653
@ -44,6 +44,9 @@ dependencies {
|
||||
|
||||
// Guava: Google test library (collections test suite)
|
||||
compile "com.google.guava:guava-testlib:19.0"
|
||||
|
||||
// OkHTTP: Simple HTTP library.
|
||||
compile 'com.squareup.okhttp3:okhttp:3.3.1'
|
||||
}
|
||||
|
||||
quasarScan.dependsOn('classes', ':core:classes', ':contracts:classes')
|
||||
|
@ -0,0 +1,17 @@
|
||||
package com.r3corda.testing.http
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper
|
||||
import com.google.common.net.HostAndPort
|
||||
import java.net.URL
|
||||
|
||||
class HttpApi(val root: URL) {
|
||||
fun putJson(path: String, data: Any) = HttpUtils.putJson(URL(root, path), toJson(data))
|
||||
fun postJson(path: String, data: Any) = HttpUtils.postJson(URL(root, path), toJson(data))
|
||||
|
||||
private fun toJson(any: Any) = ObjectMapper().writeValueAsString(any)
|
||||
|
||||
companion object {
|
||||
fun fromHostAndPort(hostAndPort: HostAndPort, base: String, protocol: String = "http"): HttpApi
|
||||
= HttpApi(URL("$protocol://$hostAndPort/$base/"))
|
||||
}
|
||||
}
|
@ -0,0 +1,37 @@
|
||||
package com.r3corda.testing.http
|
||||
|
||||
import com.r3corda.core.utilities.loggerFor
|
||||
import okhttp3.*
|
||||
import java.net.URL
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/**
|
||||
* A small set of utilities for making HttpCalls, aimed at demos and tests.
|
||||
*/
|
||||
object HttpUtils {
|
||||
private val logger = loggerFor<HttpUtils>()
|
||||
private val client by lazy {
|
||||
OkHttpClient.Builder()
|
||||
.connectTimeout(5, TimeUnit.SECONDS)
|
||||
.readTimeout(60, TimeUnit.SECONDS).build()
|
||||
}
|
||||
|
||||
fun putJson(url: URL, data: String) : Boolean {
|
||||
val body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), data)
|
||||
return makeRequest(Request.Builder().url(url).put(body).build())
|
||||
}
|
||||
|
||||
fun postJson(url: URL, data: String) : Boolean {
|
||||
val body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), data)
|
||||
return makeRequest(Request.Builder().url(url).post(body).build())
|
||||
}
|
||||
|
||||
private fun makeRequest(request: Request): Boolean {
|
||||
val response = client.newCall(request).execute()
|
||||
|
||||
if (!response.isSuccessful) {
|
||||
logger.error("Could not fulfill HTTP request. Status Code: ${response.code()}. Message: ${response.body().string()}")
|
||||
}
|
||||
return response.isSuccessful
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user