• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala HttpResponse类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中org.apache.http.HttpResponse的典型用法代码示例。如果您正苦于以下问题:Scala HttpResponse类的具体用法?Scala HttpResponse怎么用?Scala HttpResponse使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了HttpResponse类的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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()
    }
  }

} 
开发者ID:Dwolla,项目名称:scala-cloudflare,代码行数:47,代码来源:CloudflareApiExecutorSpec.scala


示例2: 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()
  }
} 
开发者ID:TokisakiFun,项目名称:Katipo,代码行数:55,代码来源:AsynCallback.scala


示例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()

} 
开发者ID:jdevelop,项目名称:rpi-jenkins,代码行数:56,代码来源:HTTPClient.scala


示例4: CustomFieldResourceSpec

//设置package包名称以及导入依赖的类
package redmine4s.api.resource

import org.apache.http.HttpResponse
import org.apache.http.client.HttpClient
import org.apache.http.client.methods.HttpGet
import org.scalatest.{DiagrammedAssertions, FlatSpec}
import org.scalatest.mockito.MockitoSugar
import org.mockito.Matchers._
import org.mockito.Mockito._
import org.slf4j.{Logger, LoggerFactory}
import redmine4s.Redmine
import redmine4s.auth.Authorization
import redmine4s.conf.Configuration

class CustomFieldResourceSpec extends FlatSpec with DiagrammedAssertions with MockitoSugar {
  "CustomFieldResource.listCustomFields" should "POST simple HTTP request" in {
    val mockHttpClient = mock[HttpClient]
    val customFieldResource = new CustomFieldResource {
      override protected val httpClient: HttpClient = mock[HttpClient]
      override protected val configuration: Configuration = mock[Configuration]
      override protected val authorization: Option[Authorization] = Some(mock[Authorization])
      override protected val logger: Logger = LoggerFactory.getLogger("nolog")
      override protected val redmine: Redmine = mock[Redmine]
      when(authorization.get.header).thenReturn(("HttpHeaderKey", "HttpHeaderValue"))
      when(httpClient.execute(any[HttpGet])).thenReturn(mock[HttpResponse])
    }

    val customFields = customFieldResource.listCustomFields()
    assert(customFields.toList.length === 2)
  }
} 
开发者ID:tomingtoming,项目名称:redmine4s,代码行数:32,代码来源:CustomFieldResourceSpec.scala


示例5: ScalaFutureCallbackImpl

//设置package包名称以及导入依赖的类
package services

import model.{Error, HttpError, JsonParsingError}
import org.apache.http.HttpResponse
import org.apache.http.client.methods.HttpRequestBase
import org.apache.http.concurrent.FutureCallback
import org.apache.http.impl.nio.client.{CloseableHttpAsyncClient, HttpAsyncClients}
import play.api.libs.json.{JsError, JsSuccess, Json, Reads}

import scala.concurrent.{ExecutionContext, Future, Promise}

class ScalaFutureCallbackImpl[T] extends FutureCallback[T] {
  private val promise: Promise[T] = Promise()

  def cancelled(): Unit =
    promise.failure(new RuntimeException("cancelled!"))

  def completed(result: T): Unit = promise.success(result)

  def failed(ex: Exception): Unit = promise.failure(ex)

  def asFuture: Future[T] = promise.future
}

class AsyncHttpClient {

  val httpClient: CloseableHttpAsyncClient = HttpAsyncClients.createDefault()
  val callback = new ScalaFutureCallbackImpl[HttpResponse]
  httpClient.start()

  def execute(request: HttpRequestBase)(implicit ec: ExecutionContext): Future[HttpResponse] = {
    httpClient.execute(request, callback)
    callback.asFuture
  }

  def json[T](request: HttpRequestBase)(implicit readerT: Reads[T], ec: ExecutionContext) : Future[Either[Error, T]] = {
    execute(request).map { response =>
      response.getStatusLine.getStatusCode match {
        case 200 => {
          val body = scala.io.Source.fromInputStream(response.getEntity.getContent).getLines().mkString("")
          httpClient.close()
          Json.parse(body).validate[T] match {
            case JsSuccess(result, _) => Right(result)
            case JsError(e) => Left(JsonParsingError(e))
          }
        }
        case httpStatusCode: Int => Left(HttpError())
      }
    }
  }

} 
开发者ID:ionagvincent,项目名称:budget,代码行数:53,代码来源:AsyncHttpClient.scala


示例6: UserListRequestHandler

//设置package包名称以及导入依赖的类
package handlers

import com.google.inject.{Inject, Singleton}
import exceptions.{ServerNotRespondingException, ServerNotStartedException}
import org.apache.http.entity.StringEntity
import org.apache.http.protocol.{HttpContext, HttpRequestHandler}
import org.apache.http.{HttpRequest, HttpResponse}
import services.UserService
import keys.ResponseKeys._

import scala.util.{Failure, Success}

@Singleton
class UserListRequestHandler @Inject()(userService: UserService) extends HttpRequestHandler {
  override def handle(request: HttpRequest, response: HttpResponse, context: HttpContext): Unit = {
    userService.fetchOnlineUsers() match {
      case Success(users) =>
        response.setStatusCode(OK)
        response.setEntity(new StringEntity(users))
      case Failure(notRespondingException: ServerNotRespondingException) =>
        response.setStatusCode(GATEWAY_TIMEOUT)
        response.setEntity(new StringEntity(notRespondingException.getMessage))
      case Failure(notStartedException: ServerNotStartedException) =>
        response.setStatusCode(BAD_GATEWAY)
        response.setEntity(new StringEntity(notStartedException.getMessage))
      case Failure(error) =>
        response.setStatusCode(INTERNAL_SERVER_ERROR)
        response.setEntity(new StringEntity(error.getMessage))
    }
  }
} 
开发者ID:jameshforster,项目名称:ToL-Scout-Plugin,代码行数:32,代码来源:UserListRequestHandler.scala



注:本文中的org.apache.http.HttpResponse类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala DeadLetter类代码示例发布时间:2022-05-23
下一篇:
Scala SimpleRoutingApp类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap