HttpRequest 和 HttpResponse
HttpRequest and HttpResponse
All 3 Akka HTTP Client API levels use the same basic model of HttpRequest
HttpRequest
and HttpResponse
HttpResponse
.
所有 3 个 Akka HTTP 客户端 API 级别都使用相同的 HttpRequest
HttpRequest
和 HttpResponse
HttpResponse
基本模型。
Creating requests
创建请求
You can create simple GET
requests:
可以创建简单 GET
请求:
Or more complicated ones, like this POST
:
或者更复杂的请求,像这个 POST
:
- Scala
-
HttpRequest( method = HttpMethods.POST, uri = "https://userservice.example/users", entity = HttpEntity(ContentTypes.`text/plain(UTF-8)`, "data") )
- Java
-
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.
有关怎样自定义请求的更多信息,见 HttpRequest
HttpRequest
的 API 文档。
Processing responses
处理响应
When you receive a response, you can use the Marshalling API to convert the response entity into an object:
当收到一个响应,可以使用 编组 API 来将响应实体转换为一个对象:
- Scala
-
import akka.http.scaladsl.unmarshalling.Unmarshal import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._ import spray.json.DefaultJsonProtocol._ case class Pet(name: String) implicit val petFormat = jsonFormat1(Pet) val pet: Future[Pet] = Unmarshal(response).to[Pet]
- Java
-
CompletionStage<Pet> pet = Jackson.unmarshaller(Pet.class).unmarshal(response.entity(), materializer);