本文整理汇总了Scala中com.ning.http.client.Response类的典型用法代码示例。如果您正苦于以下问题:Scala Response类的具体用法?Scala Response怎么用?Scala Response使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Response类的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: HTTP_METHOD
//设置package包名称以及导入依赖的类
package net.cimadai.chatwork
import com.ning.http.client.Response
import dispatch.Defaults._
import dispatch._
import org.json4s._
import org.json4s.jackson.JsonMethods
import scala.concurrent.duration._
import scala.concurrent.{Await, TimeoutException}
trait HttpClient extends JsonMethods {
object HTTP_METHOD extends Enumeration {
val GET, POST, PUT, DELETE = Value
}
private val absoluteTimeout = 30.seconds
protected val StatusCodeUndefined = -1
implicit val formats = DefaultFormats
private val http = new Http
private def executeRequestAndAwait(uri: String, method: HTTP_METHOD.Value, params: Params): Option[Response] = {
try {
val req = url(uri).setMethod(method.toString).setParameters(params)
if (method != HTTP_METHOD.GET) {
req.addHeader("Content-Type", "application/x-www-form-urlencoded")
}
val res = Await.result(http(decorateRequest(req)), absoluteTimeout)
Option(res)
} catch {
case e: TimeoutException =>
None
}
}
}
开发者ID:cimadai,项目名称:chatwork-scala,代码行数:40,代码来源:HttpClient.scala
示例2: ApiErrorParser
//设置package包名称以及导入依赖的类
package io.corbel.sdk.error
import com.ning.http.client.Response
import grizzled.slf4j.Logging
import org.json4s.DefaultFormats
import org.json4s.JsonAST.JValue
import org.json4s.native.JsonMethods._
import scala.util.{Success, Try}
class ApiErrorParser[T](f: Response => T) extends (Response => Either[ApiError, T]) with Logging {
override def apply(res: Response): Either[ApiError, T] = res.getStatusCode match {
case ok: Int if ok / 100 == 2 => Right(f(res))
case other: Int => Left(apiErrorBody(res))
}
def apiErrorBody(res: Response): ApiError = {
val apiError = ApiError(status = res.getStatusCode)
if(!res.hasResponseBody){
apiError
}
else {
Try(parse(res.getResponseBodyAsStream)) match {
case Success(json) => completeFromJson(apiError, json)
case _ =>
warn(s"Corbel error message without expected JSON body: ${res.getStatusCode} : ${res.getResponseBody}")
apiError.copy(message = Option(res.getResponseBody))
}
}
}
def completeFromJson(apiError: ApiError, json: JValue): ApiError = {
implicit val format = DefaultFormats
val c = (json \ "error").extractOpt[String]
val m = (json \ "errorDescription").extractOpt[String]
apiError.copy(errorCode = c, message = m)
}
}
开发者ID:devialab,项目名称:corbel-sdk,代码行数:41,代码来源:ApiErrorParser.scala
示例3: NotificationsClient
//设置package包名称以及导入依赖的类
package io.corbel.sdk.notifications
import com.ning.http.client.Response
import dispatch._
import io.corbel.sdk.auth.AuthenticationProvider._
import io.corbel.sdk.auth.{AutomaticAuthentication, UsesAuthentication}
import io.corbel.sdk.config.CorbelConfig
import io.corbel.sdk.error.ApiError
import io.corbel.sdk.error.ApiError._
import io.corbel.sdk.http.CorbelHttpClient
import io.corbel.sdk.http.CorbelHttpClient._
import io.corbel.sdk.iam._
import io.corbel.sdk.notifications.NotificationsClient._
import org.json4s.DefaultFormats
import org.json4s.native.Serialization._
import scala.concurrent.{ExecutionContext, Future}
class NotificationsClient(implicit val config: CorbelConfig) extends CorbelHttpClient with Notifications with UsesAuthentication {
implicit val formats = DefaultFormats
override def sendNotification(id: String, recipient: String, properties: Map[String, String])(implicit authenticationProvider: AuthenticationProvider = null, ec: ExecutionContext): Future[Either[ApiError, Unit]] = {
val jsonProperties = write(properties)
auth(token => {
val req = (notifications / send).json.withAuth(token) << s"""{"notificationId":"$id","recipient": "$recipient", "properties": $jsonProperties }"""
http(req.POST > response.eitherApiError).map(_.right.map(_ => {}))
})
}
private def response = (response: Response) => response
}
object NotificationsClient {
def apply()(implicit config: CorbelConfig) = new NotificationsClient()
def withAutomaticAuthentication(providedClientCredentials: ClientCredentials, providedUserCredentials: Option[UserCredentials] = None, providedAuthenticationOptions: AuthenticationOptions = AuthenticationOptions.default, providedExecutionContext: ExecutionContext = ExecutionContext.global)
(implicit config: CorbelConfig) =
new NotificationsClient() with AutomaticAuthentication {
override val clientCredentials: ClientCredentials = providedClientCredentials
override val userCredentials: Option[UserCredentials] = providedUserCredentials
override val authenticationOptions: AuthenticationOptions = providedAuthenticationOptions
override val executionContext: ExecutionContext = providedExecutionContext
override val authClient: AuthenticationClient = IamClient()
}
private val send = "v1.0/notification/send"
}
开发者ID:devialab,项目名称:corbel-sdk,代码行数:49,代码来源:NotificationsClient.scala
示例4: logRequestResponse
//设置package包名称以及导入依赖的类
package pl.touk.nussknacker.engine.util.service
import com.ning.http.client.Response
import com.typesafe.scalalogging.LazyLogging
import dispatch.Req
import scala.concurrent.{ExecutionContext, Future}
import scala.util.{Failure, Success}
trait RequestResponseLogging extends LazyLogging {
def logRequestResponse(req: Req)
(id: String)
(sendRequestAction: => Future[Response])
(implicit executionContext: ExecutionContext): Future[Response] = {
import collection.convert.wrapAsScala._
val request = req.toRequest
debug(
s"""${request.getMethod} ${req.url} $id request:
| HEADERS:
|${request.getHeaders.entrySet().map(e => " " + e.getKey + ": " + e.getValue.mkString(" ")).mkString("\n")}
| CONTENT:
| ${Option(request.getStringData).getOrElse("")}""".stripMargin)
val result = sendRequestAction
result.onComplete {
case Success(response) =>
debug(
s"""${request.getMethod} ${req.url} $id response:
| STATUS: ${response.getStatusCode} ${response.getStatusText}
| HEADERS:
|${response.getHeaders.entrySet().map(e => " " + e.getKey + ": " + e.getValue.mkString(" ")).mkString("\n")}
| CONTENT:
| ${response.getResponseBody}""".stripMargin)
case Failure(ex) =>
logFailure(req, id, ex)
}
result
}
def logFailure(req: Req, id: String, ex: Throwable): Unit = {
logger.error(s"${req.url} $id error", ex)
}
def debug(obj: =>String) = logger.debug(obj)
}
开发者ID:TouK,项目名称:nussknacker,代码行数:46,代码来源:RequestResponseLogging.scala
示例5: Secrets
//设置package包名称以及导入依赖的类
package janstenpickle.vault.core
import com.ning.http.client.Response
import janstenpickle.scala.syntax.SyntaxRequest._
import janstenpickle.scala.syntax.ResponseSyntax._
import janstenpickle.scala.syntax.VaultConfigSyntax._
import uscala.concurrent.result.AsyncResult
import uscala.result.Result
import scala.concurrent.ExecutionContext
// scalastyle:off magic.number
case class Secrets(config: VaultConfig, backend: String) {
def get(key: String, subKey: String = "value")
(implicit ec: ExecutionContext): AsyncResult[String, String] =
getAll(key).flatMapR(x =>
Result.fromOption(x.get(subKey),
s"Cannot find sub-key $subKey in secret $key"))
def getAll(key: String)
(implicit ec: ExecutionContext): AsyncResult[String, Map[String, String]] =
config.authenticatedRequest(path(key))(_.get).
execute.
acceptStatusCodes(200).
extractFromJson[Map[String, String]](_.downField("data"))
def set(key: String, value: String)
(implicit ec: ExecutionContext): AsyncResult[String, Response] =
set(key, "value", value)
def set(key: String, subKey: String, value: String)
(implicit ec: ExecutionContext): AsyncResult[String, Response] =
set(key, Map(subKey -> value))
def set(key: String, values: Map[String, String])
(implicit ec: ExecutionContext): AsyncResult[String, Response] =
config.authenticatedRequest(path(key))(_.post(values)).
execute.
acceptStatusCodes(204)
def list(implicit ec: ExecutionContext): AsyncResult[String, List[String]] =
config.authenticatedRequest(backend)(
_.addQueryParameter("list", true.toString).get).
execute.
acceptStatusCodes(200).
extractFromJson[List[String]](_.downField("data").downField("keys"))
def path(key: String): String = s"$backend/$key"
}
// scalastyle:on magic.number
开发者ID:janstenpickle,项目名称:scala-vault,代码行数:51,代码来源:Secrets.scala
示例6: UserPass
//设置package包名称以及导入依赖的类
package janstenpickle.vault.manage
import com.ning.http.client.Response
import janstenpickle.scala.syntax.OptionSyntax._
import janstenpickle.scala.syntax.SyntaxRequest._
import janstenpickle.scala.syntax.ResponseSyntax._
import janstenpickle.scala.syntax.VaultConfigSyntax._
import janstenpickle.vault.core.VaultConfig
import uscala.concurrent.result.AsyncResult
import scala.concurrent.ExecutionContext
// scalastyle:off magic.number
case class UserPass(config: VaultConfig) {
final val DefaultClient = "userpass"
def create(username: String,
password: String,
ttl: Int,
policies: Option[List[String]] = None,
client: String = DefaultClient)
(implicit ec: ExecutionContext): AsyncResult[String, Response] =
config.authenticatedRequest(s"auth/$client/users/$username")(
_.post(policies.map(_.mkString(",")).toMap("policies") ++
Map("username" -> username,
"password" -> password,
"ttl" -> s"${ttl}s"))
).execute.acceptStatusCodes(204)
def delete(username: String, client: String = DefaultClient)
(implicit ec: ExecutionContext): AsyncResult[String, Response] =
config.authenticatedRequest(s"auth/$client/users/$username")(_.delete).
execute.
acceptStatusCodes(204)
def setPassword(
username: String,
password: String,
client: String = DefaultClient
)(implicit ec: ExecutionContext): AsyncResult[String, Response] =
config.authenticatedRequest(s"auth/$client/users/$username/password")(
_.post(Map("username" -> username, "password" -> password))
).execute.acceptStatusCodes(204)
def setPolicies(
username: String,
policies: List[String],
client: String = DefaultClient
)(implicit ec: ExecutionContext): AsyncResult[String, Response] =
config.authenticatedRequest(s"auth/$client/users/$username/policies")(
_.post(Map("username" -> username, "policies" -> policies.mkString(",")))
).execute.acceptStatusCodes(204)
}
// scalastyle:on magic.number
开发者ID:janstenpickle,项目名称:scala-vault,代码行数:54,代码来源:UserPass.scala
示例7: Http
//设置package包名称以及导入依赖的类
package com.bhivelab.corl
import java.util.concurrent.TimeUnit
import com.ning.http.client.{AsyncHttpClient, Request, RequestBuilder, Response}
import scala.concurrent.{ExecutionContext, Future}
object Http {
def apply(req: HttpRequest)(implicit executionContext: ExecutionContext): Future[HttpResponse] = {
Future {
val client = new AsyncHttpClient()
val response = client.executeRequest(requestTransform(req)).get(60, TimeUnit.SECONDS)
client.close()
responseTransform(response)
}
}
private def requestTransform(req: HttpRequest): Request = {
val rb = new RequestBuilder(req.verb.verb).setUrl(req.url)
req.headers.foreach {
case (key,value) => rb.setHeader(key,value)
}
req.data match {
case Some(body) => rb.setBody(body)
case None =>
}
rb.build()
}
private def responseTransform(resp: Response): HttpResponse =
HttpResponse(resp.getStatusCode, resp.getResponseBodyAsBytes)
}
开发者ID:BHiveLab,项目名称:corl,代码行数:37,代码来源:Http.scala
注:本文中的com.ning.http.client.Response类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论