本文整理汇总了Scala中org.apache.http.util.EntityUtils类的典型用法代码示例。如果您正苦于以下问题:Scala EntityUtils类的具体用法?Scala EntityUtils怎么用?Scala EntityUtils使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了EntityUtils类的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: HttpSecondariesExecutor
//设置package包名称以及导入依赖的类
package com.uglylabs.httpduplicator
import com.typesafe.scalalogging.Logger
import Utils._
import org.apache.http.util.EntityUtils
class HttpSecondariesExecutor(poolSize: Int, config: ServerConfig) {
private val log = Logger[HttpSecondariesExecutor]
private val client = createHttpClient(config)
import java.util.concurrent.Executors
import scala.concurrent._
implicit private val ec = new ExecutionContext {
val threadPool = Executors.newFixedThreadPool(poolSize)
def execute(runnable: Runnable) =
threadPool.submit(runnable)
def reportFailure(t: Throwable) =
log.error("Thread pool error", t)
}
def enqueue(target: HttpTarget, request: HttpRequest) {
Future {
log.debug("Send request to secondary target: {}\n{}", target, formatRequest(request))
val response = timing(s"Processing time for secondary $target : %dms", log.debug(_)) {
client.execute(target.toHttpHost, request)
}
log.debug("Receive response from secondary target: {}\n{}", target, formatResponse(response))
// release connection resources allocated to receive entity content
EntityUtils.consume(response.getEntity())
}.onFailure {
case e => log.error(s"Error serve request to target: $target", e)
}
}
}
示例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: AsynCallback
//设置package包名称以及导入依赖的类
package indi.lewis.spider.http
import indi.lewis.spider.thread.{HttpResultProcessor, Job}
import org.apache.http.HttpResponse
import org.apache.http.concurrent.FutureCallback
import org.apache.http.util.EntityUtils
class AsynCallback(attach :UserRequest,channel:HttpResultProcessor,val runner:HttpAsynRunner) extends FutureCallback[HttpResponse]{
def getAttach():UserRequest=attach
private var firstTimeTry=true;
override def cancelled(): Unit = {
channel.addJob(new AsynCallback.NestJob((attach,0,null),f = ()=>throw new RuntimeException("task canceld")))
}
override def completed(response: HttpResponse): Unit = {
lazy val nest ={
var result:String=null;
var nest:(UserRequest,Int,String)=null;
val entity = response.getEntity() ;
if(entity!=null){
val encoding=entity.getContentEncoding() ;
val charset="UTF-8";
result=EntityUtils.toString(entity,if(encoding==null) charset else encoding .getValue);
}
EntityUtils.consume(entity)
(attach,response.getStatusLine.getStatusCode,result);
}
channel.addJob(new AsynCallback.NestJob(nest,()=>{ }))
}
override def failed(ex: Exception): Unit = {
if(runner.getRetryBeforeThrowSocketTimeout() && firstTimeTry){
runner.addRetryJob(this);
this.firstTimeTry=false;
}else{
channel.addJob(new AsynCallback.NestJob((attach,0,null),()=>throw ex))
}
}
}
object AsynCallback {
class NestJob(d : =>(UserRequest,Int,String),f:()=>Unit) extends Job[(UserRequest,Int,String)]{
override def attach(): (UserRequest, Int, String) = d
override def run(): Unit = f()
}
}
示例4: Client
//设置package包名称以及导入依赖的类
package com.stulsoft.mailgun4s
import org.apache.http.auth.{AuthScope, UsernamePasswordCredentials}
import org.apache.http.client.entity.UrlEncodedFormEntity
import org.apache.http.client.methods.{CloseableHttpResponse, HttpPost}
import org.apache.http.impl.client.{BasicCredentialsProvider, HttpClients}
import org.apache.http.message.BasicNameValuePair
import org.apache.http.util.EntityUtils
import org.apache.http.{HttpStatus, NameValuePair}
class Client {
private lazy val conf = new Config
def sendMail(mail: Mail): Unit = {
val url = conf.urlToSendMessage.format(conf.apiVersion, conf.domain)
val post = new HttpPost(url)
val credentials = new UsernamePasswordCredentials("api", conf.apiKey)
val credentialsProvider = new BasicCredentialsProvider()
credentialsProvider.setCredentials(new AuthScope("api.mailgun.net", 443), credentials)
val httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build()
val params = new java.util.ArrayList[NameValuePair]()
params.add(new BasicNameValuePair("from", mail.from))
params.add(new BasicNameValuePair("to", mail.to))
mail.cc.foreach(cc => params.add(new BasicNameValuePair("cc", cc)))
params.add(new BasicNameValuePair("subject", mail.subject))
params.add(new BasicNameValuePair(mail.body.bodyType, mail.body.bodyContent))
post.setEntity(new UrlEncodedFormEntity(params))
var response: CloseableHttpResponse = null
try {
response = httpClient.execute(post)
println(s"response.setStatusCode: ${response.getStatusLine}")
if (response.getStatusLine.getStatusCode == HttpStatus.SC_OK) {
val entity = response.getEntity
println(s"Response: ${EntityUtils.toString(entity)}")
EntityUtils.consume(entity)
}
}
catch {
case e: Exception => println(e.getMessage)
}
finally {
if (response != null)
response.close()
}
}
}
object tt extends App {
val m = Mail("[email protected]", "[email protected]", None, "test 3", HtmlBody("<htm><h1>Header</h1>text</html>"))
new Client sendMail m
}
示例5: AzureStorageRestClient
//设置package包名称以及导入依赖的类
package freedomandy.client
import freedomandy.exception.BaseException
import org.apache.http.client.methods.{CloseableHttpResponse, HttpPut}
import org.apache.http.entity.ByteArrayEntity
import org.apache.http.util.EntityUtils
import org.slf4j.{Logger, LoggerFactory}
object AzureStorageRestClient extends HttpClient {
val log: Logger = LoggerFactory.getLogger(this.getClass)
def putBlock(destination: String, chunk: Array[Byte]): Unit = {
val put:HttpPut = new HttpPut(destination)
put.setHeader("Content-type", "application/octet-stream")
val entity = new ByteArrayEntity(chunk)
put.setEntity(entity)
try {
val response:CloseableHttpResponse = client.execute(put)
log.debug("Response: " + response.toString)
val statusCode: Int = response.getStatusLine.getStatusCode
val entity = response.getEntity
val result = if (entity == null) "" else EntityUtils.toString(entity)
response.close
if (statusCode != 201) {
log.info("result: " + result)
throw BaseException("Failed to put block")
}
} catch {
case e: Throwable =>
log.info(e.getMessage)
throw e
}
}
}
示例6: ModuleUpdatesService
//设置package包名称以及导入依赖的类
package org.jmotor.sbt.service
import java.util.concurrent.{Executors, TimeUnit}
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.{CloseableHttpClient, HttpClients}
import org.apache.http.util.EntityUtils
import org.jmotor.sbt.model.{ModuleStatus, Status}
import org.jmotor.sbt.util.ModuleStatusParser
import sbt.ModuleID
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.concurrent.{Await, ExecutionContext, Future}
object ModuleUpdatesService {
private[this] val updatesHost = "https://stack-badges.herokuapp.com"
private[this] val hc: CloseableHttpClient = HttpClients.custom()
.setMaxConnTotal(20)
.setMaxConnPerRoute(20)
.setConnectionTimeToLive(5, TimeUnit.MINUTES).build()
private[this] val executionContext = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(10))
def resolve(modules: Seq[ModuleID]): Seq[ModuleStatus] = {
val result = Future.traverse(modules)(check)
Await.result(result, 1.minutes)
}
private[this] def check(module: ModuleID): Future[ModuleStatus] = {
val location = s"$updatesHost/maven-central/resolves/${module.organization}/${module.name}/${module.revision}"
val get = new HttpGet(location)
Future {
hc.execute(get)
}(executionContext) map { response ?
response.getStatusLine.getStatusCode match {
case s if s / 100 == 2 ?
val body = EntityUtils.toString(response.getEntity, "utf-8")
val (status, version) = ModuleStatusParser.parse(body)
ModuleStatus(module.organization, module.name, module.revision, Status.withName(status), version)
case 404 ? ModuleStatus(module.organization, module.name, module.revision, Status.NotFound, "")
case _ ? ModuleStatus(module.organization, module.name, module.revision, Status.Error, "")
}
} recover {
case t: Throwable ? ModuleStatus(module.organization, module.name, module.revision, Status.Error, t.getLocalizedMessage)
}
}
}