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

Scala HttpResponse类代码示例

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

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



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

示例1: DeputadosService

//设置package包名称以及导入依赖的类
package com.nakamura.camara.deputados

import com.nakamura.camara.deputados.deputado.{Deputado}
import org.apache.spark.sql.{SaveMode, SparkSession}

import scala.util.{Failure, Success, Try}
import scalaj.http.{Http, HttpResponse}


class DeputadosService(spark: SparkSession) {
  // For implicit conversions like converting RDDs to DataFrames
  import spark.implicits._

  private val logger = org.log4s.getLogger
  private val obterDeputadosEndpoint = "http://www.camara.leg.br/SitCamaraWS/Deputados.asmx/ObterDeputados"

  def getDeputados(): Try[Seq[Deputado]] = {
    logger.info(s"Sending request for deputados...")
    val response: HttpResponse[String] = Http(obterDeputadosEndpoint).postForm.asString
    if (response.isSuccess) {
      Try {
        val xml = scala.xml.XML.loadString(response.body)
        val deputadosNode = xml \\ "deputado"
        val deputados = deputadosNode.map(DeputadoUtils.fromXml)
        logger.info(s"Found ${deputados.length} deputados")
        deputados
      }
    } else {
      Failure(new Error("Request failed."))
    }
  }

  def fetchAndStoreDeputadosData(saveMode: SaveMode = SaveMode.ErrorIfExists): Unit = {
    getDeputados() match {
      case Success(deputados) =>
        val deputadossDs = deputados.toDS()
        deputadossDs.write.mode(saveMode)
          .format("json")
          .save(s"./data/deputados/")
      case Failure(err) =>
        logger.error(s"Failed to save deputados with $err")
    }
  }
} 
开发者ID:akionakamura,项目名称:camara,代码行数:45,代码来源:DeputadosService.scala


示例2: ProviderClient

//设置package包名称以及导入依赖的类
package com.latamautos


import org.json4s.DefaultFormats
import org.json4s.native.JsonParser._

import scalaj.http.{Http, HttpResponse}

object ProviderClient {

  private implicit val formats = DefaultFormats

  def fetchResults(baseUrl: String): Option[Question] = {
    println(baseUrl + "/test")
    Http(baseUrl + "/test").asString match {
      case r: HttpResponse[String] if r.is2xx =>
        parse(r.body).extractOpt[Question]
      case _ =>
        None
    }
  }

  def fetchAuthToken(host: String, port: Int, name: String): Option[Token] = {
    Http("http://" + host + ":" + port + "/auth_token?name=" + name)
      .headers(("Accept", "application/json"), ("Name", name))
      .asString match {
      case r: HttpResponse[String] if r.is2xx =>
        println(">> " + r)
        parse(r.body).extractOpt[Token]

      case r: HttpResponse[String] =>
        println("<< " + r)
        None
    }
  }

}

case class Question(id: String, title: String, text: String)

case class Token(token: String) 
开发者ID:haroldport,项目名称:consumer-pact-2,代码行数:42,代码来源:ProviderClient.scala


示例3: SimpleHttpClientTest

//设置package包名称以及导入依赖的类
package org.ebayopensource.regression.internal.http

import java.net.URI

import org.ebayopensource.regression.UnitSpec
import org.ebayopensource.regression.internal.reader.HttpMethods

import scalaj.http.{BaseHttp, HttpOptions, HttpRequest, HttpResponse}


// scalastyle:off
class SimpleHttpClientTest extends UnitSpec {

  def getClient(code: Int, body: String, headers: Map[String, IndexedSeq[String]]) : BaseHttp = {
    val client = mock[BaseHttp]

    val httpRequest = mock[HttpRequest]
    (httpRequest.headers(_:Map[String, String])).expects(*).returns(httpRequest)
    (httpRequest.method(_:String)).expects(*).returns(httpRequest)
    (httpRequest.option(_:HttpOptions.HttpOption)).expects(*).returns(httpRequest)
    (httpRequest.postData(_:String)).expects(*).returns(httpRequest)
    (httpRequest.timeout(_:Int, _:Int)).expects(*,*).returns(httpRequest)
    (httpRequest.asString _).expects().returns(HttpResponse[String](body, code, headers))

    (client.apply _).expects(*).returns(httpRequest)
    client
  }

  "A simple HTTP client" should "return the HTTP response when successful" in {
    val responseBody = """{"name":"regressr"}"""
    val client = new SimpleHttpClient(getClient(200, responseBody, Map()))
    val response = client.execute(HTTPRequest(new URI(""), Map(), HttpMethods.GET, Some("")))
    assert(response.isSuccess)
    assert(response.get.status == 200)
    assert(response.get.body.isDefined)
    assert(response.get.body.get == responseBody)
  }
}
// scalastyle:on 
开发者ID:eBay,项目名称:regressr,代码行数:40,代码来源:SimpleHttpClientTest.scala


示例4: Hello

//设置package包名称以及导入依赖的类
package com.example

import scalaj.http.{Http, HttpResponse}


object Hello {
  def main(args: Array[String]): Unit = {
    val response: HttpResponse[String] = Http("http://www.shigemk2.com").asString
    println(response.body)
    println(response.code)
    println(response.headers)
    println(response.cookies)
    println("Hello, world!")
  }
} 
开发者ID:shigemk2,项目名称:my-scalaj-http-sample,代码行数:16,代码来源:Hello.scala


示例5: ChatWorkApiResponse

//设置package包名称以及导入依赖的类
package tv.kazu.chatwork4s

import play.api.libs.json.{JsNull, Reads, Json, JsValue}
import tv.kazu.chatwork4s.models._

import scalaj.http.HttpResponse

class ChatWorkApiResponse(val httpResponse: HttpResponse[String]) {
  val body = if (!httpResponse.body.isEmpty) Some(httpResponse.body) else None
  val jsValue: JsValue = body map { bodyStr =>
    Json.parse(bodyStr)
  } getOrElse {
    JsNull
  }

  def as[T](implicit reads: Reads[T]): T = {
    jsValue.as[T]
  }

  def asEither[T](implicit reads: Reads[T]): Either[List[String], T] = {
    if (httpResponse.isSuccess) {
      Right(jsValue.as[T])
    } else {
      Left((jsValue \ "errors").get.as[List[String]])
    }
  }
}

object ChatWorkApiResponse {
  object Implicits {
    import com.github.tototoshi.play.json.JsonNaming

    implicit val userReads: Reads[User] = JsonNaming.snakecase(Json.reads[User])
    implicit val userMiniReads: Reads[UserMini] = JsonNaming.snakecase(Json.reads[UserMini])
    implicit val userFullReads: Reads[UserFull] = JsonNaming.snakecase(Json.reads[UserFull])
    implicit val roomReads: Reads[Room] = JsonNaming.snakecase(Json.reads[Room])
    implicit val messageReads: Reads[Message] = JsonNaming.snakecase(Json.reads[Message])
  }
} 
开发者ID:k4200,项目名称:chatwork4s,代码行数:40,代码来源:ChatWorkApiResponse.scala


示例6: GithubClient

//设置package包名称以及导入依赖的类
package us.grider.ghexplorer

import scalaj.http.{ Http, HttpResponse }

object GithubClient {
  val BaseURL = "https://api.github.com"

  def runCommand(cmd: Command): HttpResponse[String] = {
    val path = cmd match {
      case ListPRs(repo) => s"/repos/$repo/pulls"
      case _ => throw new Exception("Github client doesn't know how to request " + cmd)
    }

    Http(BaseURL + path).asString
  }
} 
开发者ID:mrerrormessage,项目名称:gh-explorer,代码行数:17,代码来源:GithubClient.scala


示例7: Interpret

//设置package包名称以及导入依赖的类
package us.grider.ghexplorer

import scalaj.http.HttpResponse

import org.json4s.{ JArray, JField, JInt, JObject, JString }
import org.json4s.native.JsonMethods.parse

object Interpret {
  def apply(command: Command, http: Command => HttpResponse[String]): List[Int] = {
    command match {
      case ListPRs(repo) =>
        val res = http(command)
        val parsedBody = parse(res.body)
        if (res.code >= 400) {
          val errorMessage = 
            (parsedBody \ "message") match {
              case JString(err) => err
              case _ => "Error while attempting to list PRs"
            }
          throw new Exception(errorMessage)
        } else {
          parsedBody match {
            case JArray(vals) => vals.collect {
              case obj: JObject => obj \ "id"
            }.collect {
              case JInt(i) => i.toInt
            }
            case _ => List()
          }
        }

      case _ => List()
    }
  }
} 
开发者ID:mrerrormessage,项目名称:gh-explorer,代码行数:36,代码来源:Interpret.scala


示例8: InterpreterSpec

//设置package包名称以及导入依赖的类
package us.grider.ghexplorer

import org.scalatest.FunSpec

import scala.io.Source

import scalaj.http.HttpResponse

class InterpreterSpec extends FunSpec {
  def errorResponse = HttpResponse[String]("""{"message": "bad list PR request"}""", 400, Map())

  lazy val PRResponseString = Source.fromInputStream(getClass.getClassLoader.getResourceAsStream("PRListSuccess.json")).mkString

  def listPRResponse = HttpResponse[String](PRResponseString, 200, Map())
  describe("listing a PR") {
    it("should return an error when the response is not a 200") {
      try {
        Interpret(ListPRs("foo/bar"), Function.const(errorResponse))
        fail("expected exception to be raised on error")
      } catch {
        case ex: Exception =>
          assert(ex.getMessage == "bad list PR request")
      }
    }
    it("should return a list of string maps when the response is successful") {
      val prList = Interpret(ListPRs("foo/bar"), Function.const(listPRResponse))
      assert(prList.length == 1)
      assert(prList.head == 1)
    }
  }
} 
开发者ID:mrerrormessage,项目名称:gh-explorer,代码行数:32,代码来源:InterpreterSpec.scala


示例9: getResponseBody

//设置package包名称以及导入依赖的类
package uk.ac.ncl.openlab.intake24.api.client

import io.circe.Decoder
import uk.ac.ncl.openlab.intake24.api.shared.ErrorDescription

import scalaj.http.HttpResponse
import io.circe.generic.auto._

trait ApiResponseParser extends JsonParser {

  private def getResponseBody(response: HttpResponse[String]): Either[ApiError, String] = response.code match {
    case 200 => Right(response.body)
    case 401 => Left(ApiError.RequestFailed(401, "Forbidden", "Forbidden"))
    case 403 => Left(ApiError.RequestFailed(403, "Unauthorized", "Unauthorized"))
    case code =>
      fromJson[ErrorDescription](response.body) match {
        case Right(errorDescription) => Left(ApiError.RequestFailed(code, errorDescription.errorCode, errorDescription.errorMessage))
        case Left(e) => Left(ApiError.ErrorParseFailed(response.code, e))
      }
  }

  protected def parseApiResponseDiscardBody(response: HttpResponse[String]): Either[ApiError, Unit] = getResponseBody(response).right.map(_ => ())

  protected def parseApiResponse[T](response: HttpResponse[String])(implicit decoder: Decoder[T]): Either[ApiError, T] =
    getResponseBody(response) match {
      case Right(body) =>
        fromJson[T](body) match {
          case Right(result) => Right(result)
          case Left(e) => Left(ApiError.ResultParseFailed(e))
        }
      case Left(e) => Left(e)
    }
} 
开发者ID:digitalinteraction,项目名称:intake24,代码行数:34,代码来源:ApiResponseParser.scala


示例10: VoteProjectCollector

//设置package包名称以及导入依赖的类
package ua.home.politics

import akka.actor.Actor
import akka.actor.Actor.Receive
import ua.home.politics.VoteProjectCollector.ProcessVoteProject
import ua.home.politics.model.VoteProject

import scalaj.http.{Http, HttpRequest, HttpResponse}


class VoteProjectCollector extends Actor {
  override def receive: Receive = {
    case ProcessVoteProject(url) => processVoteProject(url)
  }


  def processVoteProject(url: String): Unit = {
    val voteProject = loadVoteProject(url)
  }
  def loadVoteProject(url: String) : VoteProject = {
    val request: HttpRequest = Http(url)
    val response: HttpResponse[String] = request.asString
    new VoteProject(null, name = null, number = null, null, category = null, votes = null)
  }
}

object VoteProjectCollector {
  case class ProcessVoteProject(url: String)
} 
开发者ID:m-labazov,项目名称:ua-politics,代码行数:30,代码来源:VoteProjectCollector.scala


示例11: ImpressionViewedSpec

//设置package包名称以及导入依赖的类
package com.gravity.gdk.placement

import com.gravity.gdk.util.error.jsErrorToErrors
import play.api.libs.functional.syntax._
import play.api.libs.json._

import scalaj.http.HttpResponse


case class ImpressionViewedSpec(
  callbackUrl: String,
  hash: String
)

object ImpressionViewedSpec {
  lazy val empty = ImpressionViewedSpec("", "")

  def fromApiResponse(apiResponse: HttpResponse[String]): Either[Seq[Error], ImpressionViewedSpec] = {
    val impViewedHeader = "Grv-Impression-Viewed"
    apiResponse.header(impViewedHeader) match {
      case None => Left(Seq(new Error(s"API response missing header $impViewedHeader")))
      case Some(json) =>
        Json.parse(json).validate[ImpressionViewedSpec] match {
          case e: JsError => Left(jsErrorToErrors(e))
          case JsSuccess(spec, _) => Right(spec)
        }
    }
  }

  private[gdk] implicit val jsonFormat: Format[ImpressionViewedSpec] = Format(
    (
      (__ \ "callback").read[String] and
      (__ \ "hash").read[String]
    )(ImpressionViewedSpec.apply _),

    Writes(spec => Json.obj(
      "callback" -> spec.callbackUrl,
      "hash" -> spec.hash
    ))
  )
} 
开发者ID:GravityLabs,项目名称:gdk-scala,代码行数:42,代码来源:ImpressionViewedSpec.scala


示例12: RecoArticle

//设置package包名称以及导入依赖的类
package com.gravity.gdk.reco

import com.gravity.gdk.article.ArticleKey
import com.gravity.gdk.util.date
import com.gravity.gdk.util.error.jsErrorToErrors
import org.joda.time.DateTime
import play.api.libs.functional.syntax._
import play.api.libs.json._

import scalaj.http.HttpResponse


case class RecoArticle(
  articleId: ArticleKey,
  title: String,
  clickUrl: String,
  displayUrl: String,
  author: Option[String],
  imageUrl: String,
  publishTimestamp: DateTime,
  articleImpressionSlug: String
)

object RecoArticle {
  def listFromApiResponse(apiResponse: HttpResponse[String]): Either[Seq[Error], List[RecoArticle]] = {
    Json.parse(apiResponse.body).validate[List[RecoArticle]] match {
      case e: JsError => Left(jsErrorToErrors(e))
      case JsSuccess(articleList, _) => Right(articleList)
    }
  }

  private[gdk] implicit val jsonReader: Reads[RecoArticle] = (
    (__ \ "articleId").read[ArticleKey] and
    (__ \ "title").read[String] and
    (__ \ "clickUrl").read[String] and
    (__ \ "displayUrl").read[String] and
    (__ \ "author").readNullable[String] and
    (__ \ "image").read[String] and
    (__ \ "publishTimestamp").read[DateTime](date.unixTimestampJsonReader) and
    (__ \ "articleImpressionSlug").read[String]
  )(RecoArticle.apply _)
} 
开发者ID:GravityLabs,项目名称:gdk-scala,代码行数:43,代码来源:RecoArticle.scala


示例13: RecoResult

//设置package包名称以及导入依赖的类
package com.gravity.gdk.reco

import com.gravity.gdk.placement.ImpressionViewedSpec
import com.gravity.gdk.util.error.jsErrorToErrors
import play.api.libs.json._

import scalaj.http.HttpResponse


case class RecoResult(
  articles: List[RecoArticle],
  impressionViewed: ImpressionViewedSpec,
  impressionSlug: String,
  meta: Map[String, JsValue]
)

object RecoResult {
  def fromApiResponse(apiResponse: HttpResponse[String]): Either[Seq[Error], RecoResult] = {
    val articlesResult: Either[Seq[Error], List[RecoArticle]] =
      RecoArticle.listFromApiResponse(apiResponse)

    val impressionViewedResult: Either[Seq[Error], ImpressionViewedSpec] =
      ImpressionViewedSpec.fromApiResponse(apiResponse)

    val impressionSlugResult: Either[Seq[Error], String] = {
      val impSlugHeader = "Grv-Impression-Slug"

      apiResponse.header(impSlugHeader) match {
        case None => Left(Seq(new Error(s"Missing required header $impSlugHeader")))
        case Some(slug) => Right(slug)
      }
    }

    val metaResult: Either[Seq[Error], Map[String, JsValue]] = apiResponse.header("Grv-Meta") match {
      case None => Right(Map.empty)
      case Some(json) =>
        Json.parse(json).validate[Map[String, JsValue]] match {
          case e: JsError => Left(jsErrorToErrors(e))
          case JsSuccess(map, _) => Right(map)
        }
    }

    val errors = articlesResult.left.getOrElse(Seq.empty) ++
      impressionViewedResult.left.getOrElse(Seq.empty) ++
      impressionSlugResult.left.getOrElse(Seq.empty) ++
      metaResult.left.getOrElse(Seq.empty)

    if(errors.nonEmpty)
      Left(errors)
    else {
      val articles = articlesResult.right.get
      val impressionViewedSpec = impressionViewedResult.right.get
      val slug = impressionSlugResult.right.get
      val meta = metaResult.right.get

      Right(RecoResult(articles, impressionViewedSpec, slug, meta))
    }
  }
} 
开发者ID:GravityLabs,项目名称:gdk-scala,代码行数:60,代码来源:RecoResult.scala


示例14: FirstPactExample

//设置package包名称以及导入依赖的类
package com.wlodar.pactexample.first

import com.wlodar.jug.pacttest.client.ServiceClient
import org.scalatest.{FunSpec, FunSuite, Matchers}

import scalaj.http.HttpResponse

class FirstPactExample extends FunSuite with Matchers {

  import com.itv.scalapact.ScalaPactForger._

  test("Pierwszy przyk?ad na demo") {
    forgePact
      .between("tenTutajKonsument")
      .and("uslugaZewnetrzna")
      .addInteraction(
        interaction
          .description("Prosty get bez parametrów")
          .uponReceiving("/apiUslugi")
          .willRespondWith(200, "Pact dzia?a!!!")
      ).runConsumerTest{config=>

      //pokaza? kod
      val result: HttpResponse[String] =ServiceClient.call(config.baseUrl,"apiUslugi")

      result.code shouldBe 200
      result.body shouldBe "Pact dzia?a!!!"
//      result.body shouldBe "B??d"

    }
  }

} 
开发者ID:PawelWlodarski,项目名称:pacttests,代码行数:34,代码来源:FirstPactExample.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala BasicFileAttributes类代码示例发布时间:2022-05-23
下一篇:
Scala Settings类代码示例发布时间: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