Adding Custom Header to `spray.http.HttpRequest`

630 views
Skip to first unread message

Kevin Meredith

unread,
Jul 2, 2015, 7:46:54 PM7/2/15
to spray...@googlegroups.com
Is there a preferred/correct way to add a header to a `spray.http.HttpRequest`?

I wrote a method that: (1) issue HttpRequest to log onto website 
                                    (2) issue another HttpRequest with a custom header for authentication (from step #1)
            
I'm using scala.Either so that any failure will short-circuit in the monadic sequence.

However, I'm observing that, despite the token received in the first request's response, I am getting an HTTP 401 Error (Unauthorized) when 
issuing the second HTTP request.

Note, however, that I can take the token received from the first HTTP request, and then, using Chrome's Postman, issue the 2nd HTTP Request manually with success.

I tried to add a Header to my request in 2 ways. However, I suspect that I'm failing to properly add the header due to the above 401 error.

(1) At the `pipeline` level:
sendReceive ~> addHeader("X-...", "foobar") ~> unmarshal[AkanaLoginResponse]

(2) At the HttpRequest itself:
Post("foo.bar.com/bippy", message) ~> addHeader("X-...", "foobar")

I printed out the `request.headers`, observing that the ("X-..., "foobar") header appeared in the HttpRequest.

How can I verify that I'm properly adding the authentication header to the HTTP Request?

Age Mooij

unread,
Jul 3, 2015, 9:25:29 AM7/3/15
to spray...@googlegroups.com
(1) At the `pipeline` level:
sendReceive ~> addHeader("X-...", "foobar") ~> unmarshal[AkanaLoginResponse]

This will not work. You should add the header before the sendReceive step. Just reverse the two steps and you should be good.

(2) At the HttpRequest itself:
Post("foo.bar.com/bippy", message) ~> addHeader("X-...", "foobar”)

This should work.

I printed out the `request.headers`, observing that the ("X-..., "foobar") header appeared in the HttpRequest.

Are you saying that you did indeed see the header in the request of you printed out the request? If so, what is the problem you are asking about?

How can I verify that I'm properly adding the authentication header to the HTTP Request?

The client DSL has a debug logging directive similar to the one in spray-routing. Use one of the logRequest directives in the RequestBuilding trait.

Hope this helps
Age

Reply all
Reply to author
Forward
0 new messages