本文整理汇总了Scala中org.apache.http.impl.client.CloseableHttpClient类的典型用法代码示例。如果您正苦于以下问题:Scala CloseableHttpClient类的具体用法?Scala CloseableHttpClient怎么用?Scala CloseableHttpClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了CloseableHttpClient类的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: CloudflareApiExecutorSpec
//设置package包名称以及导入依赖的类
package com.dwolla.cloudflare
import org.apache.http.HttpResponse
import org.apache.http.client.methods.{CloseableHttpResponse, HttpRequestBase}
import org.apache.http.impl.client.CloseableHttpClient
import org.specs2.concurrent.ExecutionEnv
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import org.specs2.specification.Scope
class CloudflareApiExecutorSpec(implicit ee: ExecutionEnv) extends Specification with Mockito {
trait Setup extends Scope {
val authorization = CloudflareAuthorization("email", "key")
val mockHttpClient = mock[CloseableHttpClient]
val executor = new CloudflareApiExecutor(authorization) {
override lazy val httpClient = mockHttpClient
}
}
"Cloudflare API Executor" should {
"add required headers to requests" in new Setup {
val request = mock[HttpRequestBase]
private val response = mock[CloseableHttpResponse]
mockHttpClient.execute(request) returns response
val output = executor.fetch(request)(res ? Some(res))
output must beSome(response.asInstanceOf[HttpResponse]).await
there was one(request).addHeader("X-Auth-Email", authorization.email)
there was one(request).addHeader("X-Auth-Key", authorization.key)
there was one(request).addHeader("Content-Type", "application/json")
there was one(response).close()
}
"close the HttpClient on close" in new Setup {
executor.close()
there was one(mockHttpClient).close()
}
}
}
示例2: verify
//设置package包名称以及导入依赖的类
package com.malliina.aws.cognito
import java.net.URI
import java.nio.charset.StandardCharsets
import com.amazonaws.regions.Regions
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.{CloseableHttpClient, HttpClients}
import org.apache.http.util.EntityUtils
import play.api.libs.json.Json
trait Verifier {
def verify(token: RawToken): Either[JWTError, VerifiedToken]
def verifyAccess(token: RawAccessToken): Either[JWTError, AccessToken] =
verify(token).right.flatMap(JWT.access)
def verifyId(token: RawIDToken): Either[JWTError, IdToken] =
verify(token).right.flatMap(JWT.id)
}
class TokenVerifier(publicKeys: Seq[PubKey],
val expectedIssuer: Issuer) extends Verifier {
override def verify(token: RawToken): Either[JWTError, VerifiedToken] =
JWT.verifyToken(token, expectedIssuer, publicKeys)
}
object TokenVerifier {
def forUserPool(region: Regions, userPool: UserPool): TokenVerifier = {
val keySetUri = jwtSet(region, userPool)
val keys = Json.parse(fetch(keySetUri)).as[JWTKeys].keys map { key =>
PubKey(key.kid, Keys.publicKey(key))
}
val expectedIssuer = Issuer(s"https://cognito-idp.${region.getName}.amazonaws.com/$userPool")
new TokenVerifier(keys, expectedIssuer)
}
protected def jwtSet(region: Regions, userPool: UserPool): URI =
new URI(s"https://cognito-idp.${region.getName}.amazonaws.com/$userPool/.well-known/jwks.json")
def fetch(uri: URI): String = {
val http = HttpClients.createDefault()
try {
fetch(http, uri)
} finally {
http.close()
}
}
protected def fetch(http: CloseableHttpClient, uri: URI): String = {
val req = new HttpGet(uri)
val res = http execute req
try {
val entity = res.getEntity
EntityUtils.toString(entity, StandardCharsets.UTF_8)
} finally {
res.close()
}
}
}
示例3: HTTPClient
//设置package包名称以及导入依赖的类
package pi.jenkins.build
import java.io.InputStream
import java.security.cert.X509Certificate
import org.apache.http.HttpResponse
import org.apache.http.client.config.RequestConfig
import org.apache.http.config.{RegistryBuilder, SocketConfig}
import org.apache.http.conn.socket.{ConnectionSocketFactory, PlainConnectionSocketFactory}
import org.apache.http.conn.ssl.{SSLConnectionSocketFactory, SSLContexts, TrustStrategy}
import org.apache.http.impl.client.{CloseableHttpClient, HttpClients}
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager
import org.slf4j.LoggerFactory
object HTTPClient {
type StreamHandler = (String, HttpResponse) ? InputStream
private final val LOG = LoggerFactory.getLogger(HTTPClient.getClass)
private val TIMEOUT: Int = 20 * 1000
private val socketConfig: SocketConfig = SocketConfig.custom()
.setSoTimeout(TIMEOUT)
.setTcpNoDelay(true)
.build()
private val requestConfig: RequestConfig = RequestConfig.custom()
.setSocketTimeout(TIMEOUT)
.setConnectTimeout(TIMEOUT)
.build()
private val sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy {
override def isTrusted(chain: Array[X509Certificate], authType: String): Boolean = true
}).build()
private val sslsf = new SSLConnectionSocketFactory(
sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
private val socketFactoryRegistry = RegistryBuilder.create[ConnectionSocketFactory]().
register("https", sslsf).
register("http", PlainConnectionSocketFactory.INSTANCE).build()
private val cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry)
cm.setDefaultSocketConfig(socketConfig)
cm.setMaxTotal(200)
cm.setDefaultMaxPerRoute(20)
val client: CloseableHttpClient = HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(cm)
.build()
}
示例4: initHttpClient
//设置package包名称以及导入依赖的类
package freedomandy.client
import org.apache.http.Header
import org.apache.http.client.config.RequestConfig
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.ByteArrayEntity
import org.apache.http.impl.client.{BasicResponseHandler, CloseableHttpClient, HttpClients}
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager
import org.slf4j.LoggerFactory
trait HttpClient {
val logg =LoggerFactory.getLogger(this.getClass)
val client: CloseableHttpClient = initHttpClient()
var connMgr: PoolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager()
def initHttpClient(): CloseableHttpClient = {
val config = RequestConfig.custom().build()
val client: CloseableHttpClient = HttpClients.custom()
.setConnectionManager(connMgr)
.setDefaultRequestConfig(config).build()
return client
}
def close(): Unit = {
connMgr.close()
}
def handlePostRequest(url: String, headers: List[Header], jsonBody: String): String = {
val post = new HttpPost(url)
headers.foreach { post.addHeader(_) }
val entity = new ByteArrayEntity(jsonBody.getBytes("UTF-8"))
post.setEntity(entity)
val result = client.execute(post, new BasicResponseHandler())
return result
}
}
示例5: CloudFormationCustomResourceResponseWriter
//设置package包名称以及导入依赖的类
package com.dwolla.lambda.cloudformation
import org.apache.http.client.methods.HttpPut
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.{CloseableHttpClient, HttpClients}
import org.json4s.{DefaultFormats, Formats}
import org.json4s.native.Serialization._
import org.slf4j.{Logger, LoggerFactory}
import scala.concurrent.{ExecutionContext, Future}
import scala.io.Source
class CloudFormationCustomResourceResponseWriter(implicit ec: ExecutionContext) {
protected lazy val logger: Logger = LoggerFactory.getLogger("LambdaLogger")
protected implicit val formats: Formats = DefaultFormats ++ org.json4s.ext.JodaTimeSerializers.all
def httpClient: CloseableHttpClient = HttpClients.createDefault()
def logAndWriteToS3(presignedUri: String, cloudFormationCustomResourceResponse: CloudFormationCustomResourceResponse): Future[Unit] = Future {
val req = new HttpPut(presignedUri)
val jsonEntity = new StringEntity(write(cloudFormationCustomResourceResponse))
jsonEntity.setContentType("")
req.setEntity(jsonEntity)
req.addHeader("Content-Type", "")
logger.info(Source.fromInputStream(req.getEntity.getContent).mkString)
try {
val res = httpClient.execute(req)
res.close()
} finally {
httpClient.close()
}
}
}
开发者ID:Dwolla,项目名称:scala-cloudformation-custom-resource,代码行数:37,代码来源:CloudFormationCustomResourceResponseWriter.scala