Last active
August 13, 2020 16:22
-
-
Save taretmch/33a2250466dd339afbb8f2b5813ace82 to your computer and use it in GitHub Desktop.
This file contains 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 training.http | |
import akka.actor.ActorSystem | |
import akka.http.scaladsl.Http | |
import akka.http.scaladsl.model._ | |
import akka.http.scaladsl.model.headers.RawHeader | |
import akka.util.ByteString | |
import play.api.libs.json._ | |
import scala.concurrent.Await | |
import scala.concurrent.duration.Duration | |
import scala.concurrent.ExecutionContext.Implicits.global | |
/** | |
* Example: Post request with json data | |
*/ | |
object PostJson { | |
// API Endpoint | |
val URI = "http://localhost:9000/api/post/test" | |
def main(args: Array[String]): Unit = { | |
run() | |
} | |
def run(): Unit = { | |
implicit val system = ActorSystem() | |
// Json data | |
val data: JsValue = Json.parse(""" | |
{ | |
"user": { | |
"name": "tomochin", | |
"location": "Tokyo", | |
"age": "18" | |
}, | |
"message": "JSON Post test!" | |
} | |
""") | |
// Create HTTP request | |
val request = HttpRequest( | |
method = HttpMethods.POST, | |
uri = URI, | |
entity = HttpEntity( | |
contentType = ContentTypes.`application/json`, | |
data = ByteString(Json.prettyPrint(data)) | |
) | |
) | |
val process = for { | |
// Send HTTP request to server | |
response <- Http().singleRequest(request) | |
} yield response match { | |
// Handle response | |
case HttpResponse(StatusCodes.OK, _, entity, _) => | |
entity.dataBytes.runFold(ByteString(""))(_ ++ _).foreach { body => | |
println("Got response, body: " + body.utf8String) | |
} | |
case resp @ HttpResponse(code, _, _, _) => | |
println("Request failed, response code: " + code) | |
resp.discardEntityBytes() | |
} | |
Await.result(process, Duration.Inf) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment