@@ -3,13 +3,15 @@ package utils
33
44import akka .actor .ActorSystem
55import akka .http .scaladsl .Http
6- import akka .http .scaladsl .model .{HttpMethods , HttpRequest , HttpResponse , Uri }
6+ import akka .http .scaladsl .model .{HttpEntity , HttpMethods , HttpRequest , HttpResponse , MediaTypes , Uri }
77import akka .stream .{ActorMaterializer , ActorMaterializerSettings }
88import akka .util .ByteString
99
1010import scala .concurrent .{Await , Future }
1111import scala .concurrent .duration .Duration
1212import scala .util .{Failure , Success , Try }
13+ import MediaTypes ._
14+
1315
1416/** *
1517 * A blocking http client implemented using Akka HTTP
@@ -38,11 +40,44 @@ object BlockingHttpClient {
3840
3941 }
4042
43+ // data parameter will be """{"name":"Hello"}"""
44+ def doPost (uri : Uri , data : String ) = {
45+ implicit val system = ActorSystem ()
46+ implicit val executionContext = system.dispatcher
47+ implicit val materializer : ActorMaterializer = ActorMaterializer (ActorMaterializerSettings (system))
48+ val bdata = ByteString (data)
49+ try {
50+ val req : Future [HttpResponse ] = Http (system).singleRequest(HttpRequest (
51+ method = HttpMethods .POST ,
52+ uri = uri,
53+ entity = HttpEntity (`application/json`, bdata)
54+ ))
55+ Await .result(req, Duration .Inf )
56+
57+ val f = req.value.get.get.entity.dataBytes.runFold(ByteString (" " ))(_ ++ _)
58+ Await .result(f, Duration .Inf )
59+
60+ Success (f.value.get.get.utf8String)
61+ } catch {
62+ case e : Exception => Failure (e)
63+ } finally {
64+ system.terminate()
65+ Await .result(system.whenTerminated, Duration .Inf )
66+ }
67+ }
68+
4169 def executeGet (target : String , server : String ) : Try [String ] = {
4270
4371 val uri = Uri (server)
4472 doGet(uri.withPath(uri.path + target))
4573
4674 }
4775
76+ def executePost (target : String , server : String , data : String ) : Try [String ] = {
77+
78+ val uri = Uri (server)
79+ doPost(uri.withPath(uri.path + target), data)
80+
81+ }
82+
4883}
0 commit comments