Spray(11)spray-can - Http Client - Simple Example

Spray(11)spray-can - Http Client - Simple Example

1. Different Type of Client
Based on the document, there are 3 types of clients.
HttpClient -----> HttpDialog -----> Spray-client
2. HttpClient
It is asynchronous, non-blocking and actor-based HTTP/1.1 client on top of spray-io.
It is based on IOBridge and spawns new child actors for every new connection.

One HttpClient instance can handle many thousand concurrent requests. So usually, we only need on HttpClient instance, only if we need different httpClients when we have different configurations.

Example simple-http-client
There is one example simple-http-client. Build and import the example.
>git clone https://github.com/spray/spray.git
>cd spray
>vi project/plugin.sbt
addSbtPlugin("com.github.mpeltonen" % "sbt-idea" % "1.4.0")

addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.1.0")
>sbt clean
>sbt update
>sbt eclipse
>sbt gen-idea

The example project should be here, I use eclipse to import that.
/Users/carl/work/spray/spray/examples/spray-can/simple-http-client

Message Protocol
HttpClient ---> Connect/HttpClient.Connected ---> establish the connection, then we can send the requests ---> HttpRequest
Once the connection Actor get and parse the response we get ----> HttpResponse
----> decide to reuse or close the connection ----> Close

Chunked Requests and Chunked Responses
ChunkedRequestStart ----> MessageChunks ---> ChunkedMessageEnd

ChunkedResponseStart ---> MessageChunks -----> ChunkedMessageEnd

Request Timeouts
Send Confirmations
Closed Notifications
Connection Configuration
SetIdleTimeout
SetRequestTimeout

Http Headers
spray-can HttpClient always passes all received headers back to my application, only interpreted
Content-Length
Content-Type
Transfer-Encoding

SSL Support
allows outgoing connections to be SSL/TLS encrypted. HttpClient.SslEnabled

3. Fighting with the 'Latest' documents and 'Latest' Sample Codes
>git clone https://github.com/spray/spray-can.git

I am so happy I get a running example of scala/spray.

>cd spray-can
>sudo sbt "project server-example" run

This will running the server side codes which also based on spray-can, visit http://localhost:8080 to verify that.

>sudo sbt "project client-example" run

Then, I can also play with my clients.

Try to import these projects and learn from that.

But after I import the project, I do not think it is right version. So I go back and find with the project simple-http-client.
After I import these projects and clean the eclipse, it works.
spray-can
spray-http
spray-io
spray-util

See the tips, finally I found the right example version for 1.1.M7. Let's rock and roll.

SimpleExample
Some import concept

ActorSystem to run
implicit val system = ActorSystem("simple-example")

Create default spray-can HttpClient
val httpClient = DefaultHttpClient(system)

create a very basic HttpDialog that results in a Future[HttpResponse]
val responseFuture =
     HttpDialog(httpClient, "github.com")
     .send(HttpRequest(url = "/"))
     .end

In the constructor of HttpDialog, we can also put port number there.
def apply(httpClient: ActorRef, host: String, port: Int = 80, tag: Any = ())

port and tag get some default values.

How to deal with Future
responseFuture onComplete {
     case Success(response) =>
          """|Result from host:
           |status : {}
           |headers: {}
           |body   : {}""".stripMargin,
        response.status, response.headers.mkString("\n  ", "\n  ", ""), response.entity.asString
      )
      system.shutdown()
     case Failure(error) =>
          log.error("Could not get response due to {}", error)
          system.shutdown()
}

mkString is usually provide to the collection.
response.entity.asString, we got all the content from my understanding.

4. HttpDialog
HttpDialog is high level of HttpClient. We can create multiple requests in order.

5. Spray Client
Spray Client is a kind of high level with basic auth or some other things.
I successfully running it with these command under spray.
>sbt "project simple-spray-client" run

Import these dependencies
spray-client
spray-httpx

come soon...

Tips
1. Spray Version
http://spray.io/project-info/changelog/#version-1-1-m7-2012-12-19
http://repo.spray.cc/io/spray/spray-routing/1.1-M7/
https://github.com/spray/spray/tree/d18bdedcd898ff5d62acd380a30f1bd09d8741e5/examples/spray-client/simple-spray-client/src/main/scala/spray/examples

After several time, I figure out the right version for 1.1.M7 is
d18bdedcd8
>git show d18bdedcd8
commit d18bdedcd898ff5d62acd380a30f1bd09d8741e5
Author: Mathias <[email protected]>
Date:   Wed Dec 19 17:13:51 2012 +0100
>git checkout d18bdedcd898ff5d62acd380a30f1bd09d8741e5
>vi project/plugin.sbt
addSbtPlugin("io.spray" % "sbt-revolver" % "0.6.2")
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.8.5")
addSbtPlugin("com.typesafe.sbt" % "sbt-scalariform" % "1.0.1")
addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.2.0")
addSbtPlugin("com.github.mpeltonen" % "sbt-idea" % "1.4.0")


After add these lines, go with other sbt command
>sbt clean
>sbt update
>sbt eclipse
>sbt gen-idea
>git checkout -b 1.1-M7

Right now, I have the source codes and sample, I can begin from here.

2. mkString
scala> val args = Array("hello", "call")
args: Array[String] = Array(hello, call)

scala> val string = args.mkString(" ")
string: String = hello call

scala> val lists = List("hello", "kiko")
lists: List[String] = List(hello, kiko)

scala> val list_str = lists.mkString(" ")
list_str: String = hello kiko

toString is just show the object in string format, but mkString is for collection object.

Some Other Separator Strings
scala> val string = args.mkString(".")
string: String = hello.call

Specifying a prefix, separator, and suffix with mkString
scala> val numbers = List(1,2,3)
numbers: List[Int] = List(1, 2, 3)

scala> numbers.mkString("[",",","]")
res0: String = [1,2,3]

References:
http://spray.io/documentation/spray-can/http-client/
http://spray.io/documentation/spray-can/examples/

http://spray.io/documentation/spray-can/http-dialog/
https://github.com/spray/spray-can

spray client
http://spray.io/documentation/spray-client/
http://java.dzone.com/articles/spray-client-spray-and-text
https://github.com/spray/spray/wiki/spray-client
http://www.cakesolutions.net/teamblogs/2012/11/10/spray-client-spray-and-text-messages/

spray(2)spray-can
http://sillycat.iteye.com/blog/1766568


猜你喜欢

转载自sillycat.iteye.com/blog/1882919