本文整理汇总了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")
}
}
}
示例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)
示例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
示例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!")
}
}
示例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])
}
}
示例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
}
}
示例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()
}
}
}
示例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)
}
}
}
示例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)
}
}
示例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)
}
示例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
))
)
}
示例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 _)
}
示例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))
}
}
}
示例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"
}
}
}