如何将消息正文添加到 Play2.2 Scala WS GET?

问题描述 投票:0回答:2

我知道这是非常规的 - 我正在访问一个 API,该 API 需要将 JSON 对象作为 GET 请求的消息正文发布。使用 Play 2.2.2 和

play.api.libs.ws.WS

我正在尝试将消息正文添加到

WSRequestHolder
.post()
方法允许这样做,但
.get()
方法没有这样的参数。我正在考虑使用基本的
WSRequest
类而不是
WSRequestHolder
但不确定是否有更好的方法来做到这一点。

伪代码:

WS.url(url).get(Json.obj("param" -> "value"))

WS.url(url).setBody(Json.obj("param" -> "value")).get()

有什么想法吗?感谢您的帮助!

scala playframework playframework-2.2
2个回答
0
投票

如有疑问,请推出自己的解决方案。

import scala.concurrent.{ Future, Promise }
import play.api.libs.concurrent._
import play.api.libs.iteratee._
import play.api.libs.iteratee.Input._
import play.api.libs.json._
import play.api.http.{ Writeable, ContentTypeOf }
import play.api.libs.ws.WS._
import play.api.libs.ws.{SignatureCalculator, Response}
import com.ning.http.client.Realm.AuthScheme
import com.ning.http.client.PerRequestConfig


class MyRequest(
  url: String,
  headers: Map[String, Seq[String]],
  queryString: Map[String, Seq[String]],
  calc: Option[SignatureCalculator],
  auth: Option[Tuple3[String, String, AuthScheme]],
  followRedirects: Option[Boolean],
  requestTimeout: Option[Int],
  virtualHost: Option[String]

) extends WSRequestHolder(url,headers,queryString,calc,auth,followRedirects,requestTimeout,virtualHost) {

  /**
   * Perform a GET on the request asynchronously with a body.
   */
  def get[T](body: T)(implicit wrt: Writeable[T], ct: ContentTypeOf[T]): Future[Response] = prepare("POST", body).execute

  /**
   * Prepare a request
   * @param method
   * @param body
   * @param wrt
   * @param ct
   * @tparam T
   * @return
   */
  override def prepare[T](method: String, body: T)(implicit wrt: Writeable[T], ct: ContentTypeOf[T]) = {
    val request = new WSRequest(method, auth, calc).setUrl(url)
      .setHeaders(Map("Content-Type" -> Seq(ct.mimeType.getOrElse("text/plain"))) ++ headers)
      .setQueryString(queryString)
      .setBody(wrt.transform(body))
    followRedirects.map(request.setFollowRedirects)
    requestTimeout.map {
      t: Int =>
        val config = new PerRequestConfig()
        config.setRequestTimeoutInMs(t)
        request.setPerRequestConfig(config)
    }
    virtualHost.map {
      v =>
        request.setVirtualHost(v)
    }
    request
  }

}

object MyWS {
  /**
   * Prepare a new request. You can then construct it by chaining calls.
   *
   * @param url the URL to request
   */
  def url(url: String): MyRequest = new MyRequest(url, Map(), Map(), None, None, None, None, None)
}

0
投票

请求构建器包含一个

withBody
方法,即使在 GET 请求上也可用于设置正文。

val response = WS.url(url).withBody(Json.obj("param" -> "value")).get()
© www.soinside.com 2019 - 2024. All rights reserved.