String payloads to the HttpApi are assumed to be valid JSON and sent as is, previous behaviour would escape the string.

This commit is contained in:
Clinton Alexander 2016-11-04 15:59:56 +00:00
parent 9a4dcd9b58
commit 5ac679dd0e
2 changed files with 13 additions and 3 deletions

View File

@ -5,10 +5,20 @@ import com.google.common.net.HostAndPort
import java.net.URL
class HttpApi(val root: URL) {
/**
* Send a PUT with a payload to the path on the API specified.
*
* @param data String values are assumed to be valid JSON. All other values will be mapped to JSON.
*/
fun putJson(path: String, data: Any = Unit) = HttpUtils.putJson(URL(root, path), toJson(data))
/**
* Send a POST with a payload to the path on the API specified.
*
* @param data String values are assumed to be valid JSON. All other values will be mapped to JSON.
*/
fun postJson(path: String, data: Any = Unit) = HttpUtils.postJson(URL(root, path), toJson(data))
private fun toJson(any: Any) = ObjectMapper().writeValueAsString(any)
private fun toJson(any: Any) = if (any is String) any else ObjectMapper().writeValueAsString(any)
companion object {
fun fromHostAndPort(hostAndPort: HostAndPort, base: String, protocol: String = "http"): HttpApi

View File

@ -18,12 +18,12 @@ object HttpUtils {
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())
return makeRequest(Request.Builder().url(url).header("Content-Type", "application/json").post(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())
return makeRequest(Request.Builder().url(url).header("Content-Type", "application/json").post(body).build())
}
private fun makeRequest(request: Request): Boolean {