HttpRequest and HttpResponse
All 3 Apache Pekko HTTP Client API levels use the same basic model of HttpRequest
HttpRequest
and HttpResponse
HttpResponse
.
Creating requests
You can create simple GET
requests:
- Scala
-
source
HttpRequest(uri = "https://pekko.apache.org") // or: import org.apache.pekko.http.scaladsl.client.RequestBuilding.Get Get("https://pekko.apache.org") // with query params Get("https://pekko.apache.org?foo=bar")
- Java
-
source
HttpRequest.create("https://pekko.apache.org"); // with query params HttpRequest.create("https://pekko.apache.org?foo=bar");
Note
HttpRequest
HttpRequest
alsoHttpRequest
HttpRequest
’s method HttpRequest::withUri()
takes Uri
Uri
as a parameter. Query String in URI section describes a fluent API for building URIs with query parameters.
Or more complicated ones, like this POST
:
- Scala
-
source
HttpRequest( method = HttpMethods.POST, uri = "https://userservice.example/users", entity = HttpEntity(ContentTypes.`text/plain(UTF-8)`, "data")) // or: import org.apache.pekko.http.scaladsl.client.RequestBuilding.Post Post("https://userservice.example/users", "data")
- Java
-
source
HttpRequest.POST("https://userservice.example/users") .withEntity(HttpEntities.create(ContentTypes.TEXT_PLAIN_UTF8, "data"));
See the API documentation of HttpRequest
HttpRequest
for more information on how to customize your requests.
Processing responses
When you receive a response, you can use the Marshalling API to convert the response entity into an object:
- Scala
-
source
import org.apache.pekko import pekko.http.scaladsl.unmarshalling.Unmarshal import pekko.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._ import spray.json.DefaultJsonProtocol._ import spray.json.RootJsonFormat case class Pet(name: String) implicit val petFormat: RootJsonFormat[Pet] = jsonFormat1(Pet.apply) val pet: Future[Pet] = Unmarshal(response).to[Pet]
- Java
-
source
CompletionStage<Pet> pet = Jackson.unmarshaller(Pet.class).unmarshal(response.entity(), system);
1.0.1