当前位置: 首页>>代码示例>>Scala>>正文


Scala HttpRequest类代码示例

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


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

示例1: OauthSpotifyEndpoint

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

import scalaj.http.{Http, HttpRequest}

abstract class OauthSpotifyEndpoint extends SpotifyEndpoint {

  private def getOauthBearer(authToken: String): Option[String] = authToken match {
    case "" => None
    case token => Some("Bearer " + token)
  }

  private def getAuthHeaders(authToken: String): Option[Map[String, String]] = getOauthBearer(authToken) match {
    case None => None
    case Some(authHeader) => Some(Map("Authorization" -> authHeader))
  }

  protected def createRequest(authToken:String, endpoint: String): Option[HttpRequest] = {
    getAuthHeaders(authToken).map(headers => {
      Some(Http(endpoint).headers(headers))
    }).getOrElse(None)
  }

  protected def createRequest(authToken:String,
                            endpoint: String,
                            params: Seq[(String, String)]) : Option[HttpRequest] = {
    getAuthHeaders(authToken).map(headers => {
      Some(Http(endpoint).headers(headers).params(params))
    }).getOrElse(None)
  }
} 
开发者ID:Jakeway,项目名称:spotify-web-api-scala,代码行数:31,代码来源:OauthSpotifyEndpoint.scala

示例2: RecommendationsEndpoint

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

import scalaj.http.HttpRequest


object RecommendationsEndpoint extends OauthSpotifyEndpoint {

  private val recommendationsEndpoint = baseAPIUrl + "/v1/recommendations/"

  def getRecommendations(authToken: String,
                         seedArtists: Seq[String],
                         seedGenres: Seq[String],
                         seedTracks: Seq[String]): Option[HttpRequest] = {

    // spotify dictates max of 5 seed combinations from {artists, genres, tracks}

    val totalSeqLengths = seedArtists.length + seedGenres.length + seedTracks.length
    if (totalSeqLengths > 5) None
    else if (totalSeqLengths == 0) None
    else {
      val params = Seq(
        ("seed_artists", seedArtists.mkString(",")),
        ("seed_genres", seedGenres.mkString(",")),
        ("seed_tracks", seedTracks.mkString(","))
      )
      createRequest(authToken = authToken, endpoint = recommendationsEndpoint, params = params)
    }
  }
} 
开发者ID:Jakeway,项目名称:spotify-web-api-scala,代码行数:30,代码来源:RecommendationsEndpoint.scala

示例3: TestFetcher

//设置package包名称以及导入依赖的类
package com.github.catalystcode.fortis.spark.streaming.reddit.client

import org.scalatest.FlatSpec

import scalaj.http.HttpRequest

class TestFetcher(val responses: Map[Option[String], String]) extends ResponseFetcher {
  override def fetchStringResponse(request: HttpRequest): String = {
    return responses(Option(request.url))
  }
}

class TestExceptionRedditClient(val exception: Exception) extends ResponseFetcher {
  override def fetchStringResponse(request: HttpRequest): String = {
    throw exception
  }
}

class TestRedditClient extends FlatSpec {

  "The reddit client" should "produce domain objects from the json api response" in {
    val responseString = "{\"kind\": \"Listing\", \"data\": {\"facets\": {}, \"modhash\": \"\", \"children\": [{\"kind\": \"t3\", \"data\": {\"contest_mode\": false, \"subreddit_name_prefixed\": \"r/arableaks\", \"banned_by\": null, \"media_embed\": {}, \"thumbnail_width\": null, \"subreddit\": \"arableaks\", \"selftext_html\": \"<!-- SC_OFF --><div class=\\\"md\\\"><p>Trumpcare on Life Support as Senate Punts Until After the Holiday Recess</p>\\n\\n<p>by via Sputnik International</p>\\n\\n<p>URL: <a href=\\\"http://ift.tt/2s0NpQ6\\\">http://ift.tt/2s0NpQ6</a></p>\\n\\n<p>On this episode of Fault Lines, Garland and Lee discuss the GOP healthcare bill's possible demise as the Senate postpones the motion to proceed vote, the Trump Administration's latest threats against Syria Russia and China, and a recent video showing a CNN producer admitting that their Russiagate coverage is ratings driven.</p>\\n</div><!-- SC_ON -->\", \"selftext\": \"Trumpcare on Life Support as Senate Punts Until After the Holiday Recess\\n   \\n by via Sputnik International\\n   \\n URL: http://ift.tt/2s0NpQ6\\n   \\n On this episode of Fault Lines, Garland and Lee discuss the GOP healthcare bill's possible demise as the Senate postpones the motion to proceed vote, the Trump Administration's latest threats against Syria Russia and China, and a recent video showing a CNN producer admitting that their Russiagate coverage is ratings driven.\\n   \\n   \\n\", \"likes\": null, \"suggested_sort\": null, \"user_reports\": [], \"secure_media\": null, \"link_flair_text\": null, \"id\": \"6jzbmy\", \"view_count\": null, \"secure_media_embed\": {}, \"clicked\": false, \"report_reasons\": null, \"author\": \"feedreddit\", \"saved\": false, \"mod_reports\": [], \"name\": \"t3_6jzbmy\", \"score\": 1, \"approved_by\": null, \"over_18\": false, \"domain\": \"self.arableaks\", \"hidden\": false, \"preview\": {\"images\": [{\"source\": {\"url\": \"https://i.redditmedia.com/pOPChNLJ3b35UMz7K91DW95s0gtsC8yUJ7uAhCaBSO8.jpg?s=3b3da04dfc0d68a49c5f90dc12c27c03\", \"width\": 638, \"height\": 450}, \"resolutions\": [{\"url\": \"https://i.redditmedia.com/pOPChNLJ3b35UMz7K91DW95s0gtsC8yUJ7uAhCaBSO8.jpg?fit=crop&crop=faces%2Centropy&arh=2&w=108&s=82aa23c4274d0548258eb99f192db3c2\", \"width\": 108, \"height\": 76}, {\"url\": \"https://i.redditmedia.com/pOPChNLJ3b35UMz7K91DW95s0gtsC8yUJ7uAhCaBSO8.jpg?fit=crop&crop=faces%2Centropy&arh=2&w=216&s=1baeb298fabde06ccff129242201b4e7\", \"width\": 216, \"height\": 152}, {\"url\": \"https://i.redditmedia.com/pOPChNLJ3b35UMz7K91DW95s0gtsC8yUJ7uAhCaBSO8.jpg?fit=crop&crop=faces%2Centropy&arh=2&w=320&s=8f6efbbd8e6e9bcb318dc2715bf29656\", \"width\": 320, \"height\": 225}], \"variants\": {}, \"id\": \"CC_2oyPfjBKYQIiW8WEjhUeoW-jOBDYRiaYMbRq6Paw\"}], \"enabled\": false}, \"thumbnail\": \"self\", \"subreddit_id\": \"t5_33yiw\", \"edited\": false, \"link_flair_css_class\": null, \"author_flair_css_class\": null, \"gilded\": 0, \"downs\": 0, \"brand_safe\": false, \"archived\": false, \"removal_reason\": null, \"sr_detail\": {\"banner_img\": \"\", \"user_is_banned\": null, \"description\": \"\\u0639\\u0631\\u0628 of reddit, Unite!\\n\\n\\nWelcome to /r/Arableaks , a subreddit for  news/information concerning the Arab region and for those who wish to engage in constructive, civil discussion about world/Arab events . People from all organizations, groups, and tendencies are welcome.\\n\\n**Rules:**\\n\\nJust DO NOT Post comments which include, promote for racism, sexism, transphobia, rape, genocide/ethnic cleansing, fascism, homophobia or queer bashing , otherwise feel free to contribute .\", \"user_is_muted\": null, \"display_name\": \"arableaks\", \"header_img\": \"https://b.thumbs.redditmedia.com/nLji0owHL8FoKv1Fo9iAX_B7Xxh-yBetkbbopj1xjMk.png\", \"title\": \"Arab leaks\", \"user_is_moderator\": null, \"over_18\": false, \"icon_size\": null, \"icon_img\": \"\", \"display_name_prefixed\": \"r/arableaks\", \"header_size\": [169, 160], \"subscribers\": 60, \"key_color\": \"\", \"name\": \"t5_33yiw\", \"url\": \"/r/arableaks/\", \"banner_size\": null, \"user_is_contributor\": null, \"public_description\": \"\\u0639\\u0631\\u0628 of reddit!\\n\\n\\nWelcome to /r/Arableaks , People from all organizations, groups, and tendencies are welcome.\", \"subreddit_type\": \"public\", \"user_is_subscriber\": null}, \"post_hint\": \"self\", \"can_gild\": false, \"thumbnail_height\": null, \"hide_score\": true, \"spoiler\": false, \"permalink\": \"/r/arableaks/comments/6jzbmy/trumpcare_on_life_support_as_senate_punts_until/?ref=search_posts\", \"num_reports\": null, \"locked\": false, \"stickied\": false, \"created\": 1498668331.0, \"url\": \"https://www.reddit.com/r/arableaks/comments/6jzbmy/trumpcare_on_life_support_as_senate_punts_until/\", \"author_flair_text\": null, \"quarantine\": false, \"title\": \"Trumpcare on Life Support as Senate Punts Until After the Holiday Recess\", \"created_utc\": 1498639531.0, \"distinguished\": null, \"media\": null, \"num_comments\": 0, \"is_self\": true, \"visited\": false, \"subreddit_type\": \"public\", \"is_video\": false, \"ups\": 1}}, {\"kind\": \"t3\", \"data\": {\"contest_mode\": false, \"subreddit_name_prefixed\": \"r/AskEurope\", \"banned_by\": null, \"media_embed\": {}, \"thumbnail_width\": null, \"subreddit\": \"AskEurope\", \"selftext_html\": \"<!-- SC_OFF --><div class=\\\"md\\\"><p>I'm curious about different systems of healthcare from around the world, seeing the American model is not perfect (far from). I'd also like to explain what healthcare is like in mine if I get the opportunity. Here are my questions: </p>\\n\\n<blockquote>\\n<p>What country are you from?</p>\\n\\n<p>What do you like about your healthcare system?</p>\\n\\n<p>How is it paid for?</p>\\n\\n<p>Is it efficient? Cost effective, mortality rates, etc are my parameters for this question</p>\\n\\n<p>Are you satisfied with your healthcare? </p>\\n\\n<p>Are there private providers?</p>\\n\\n<p>Any personal anecdotes?</p>\\n\\n<p>What could be improved in the system?</p>\\n</blockquote>\\n\\n<p>In case you wanted to discuss American healthcare:</p>\\n\\n<blockquote>\\n<p>What have you heard about American healthcare?</p>\\n\\n<p>Do you have any questions about American healthcare for me?</p>\\n</blockquote>\\n</div><!-- SC_ON -->\", \"selftext\": \"I'm curious about different systems of healthcare from around the world, seeing the American model is not perfect (far from). I'd also like to explain what healthcare is like in mine if I get the opportunity. Here are my questions: \\n\\n>What country are you from?\\n\\n>What do you like about your healthcare system?\\n\\n>How is it paid for?\\n\\n>Is it efficient? Cost effective, mortality rates, etc are my parameters for this question\\n\\n>Are you satisfied with your healthcare? \\n\\n>Are there private providers?\\n\\n>Any personal anecdotes?\\n\\n>What could be improved in the system?\\n\\n\\nIn case you wanted to discuss American healthcare:\\n\\n>What have you heard about American healthcare?\\n\\n>Do you have any questions about American healthcare for me?\", \"likes\": null, \"suggested_sort\": null, \"user_reports\": [], \"secure_media\": null, \"link_flair_text\": \"Politics\", \"id\": \"6jzau9\", \"view_count\": null, \"secure_media_embed\": {}, \"clicked\": false, \"report_reasons\": null, \"author\": \"GlockInbound\", \"saved\": false, \"mod_reports\": [], \"name\": \"t3_6jzau9\", \"score\": 0, \"approved_by\": null, \"over_18\": false, \"domain\": \"self.AskEurope\", \"hidden\": false, \"thumbnail\": \"self\", \"subreddit_id\": \"t5_2uayg\", \"edited\": false, \"link_flair_css_class\": \"politics\", \"author_flair_css_class\": null, \"gilded\": 0, \"downs\": 0, \"brand_safe\": true, \"archived\": false, \"removal_reason\": null, \"sr_detail\": {\"banner_img\": \"\", \"user_is_banned\": null, \"description\": \"---\\n\\n**Got a question for a European, about Europe or anything Europe related? Then you came to the right place!**\\n\\n---\\n\\n**Posts from accounts younger than a month old are manually approved to avoid brigading and spam.**\\n\\n# Rules:\\n\\n[Please consult our wiki page for our posting rules.](https://www.reddit.com/r/AskEurope/wiki/rules)\\n\\n\\n# Posting Guidelines:\\n\\n 1. Be polite and courteous to everybody.\\n\\n 2. [Rediquette](http://www.reddit.com/wiki/reddiquette) should always be followed!\\n\\n 3. Have fun and learn about Europe!   \\n\\n 4. Posting in English is recommended for accessibility but is not mandatory. Please translate links and text where possible.\\n\\n \\n# General Info:\\n\\n- [EU on wikipedia](http://en.wikipedia.org/wiki/European_Union)\\n\\n- [European Foodbank Charities](http://www.eurofoodbank.eu/portail/index.php?option=com_content&view=category&layout=blog&id=12&Itemid=30&lang=en)\\n\\n- [Phone plans / SIM cards advice](http://prepaid-data-sim-card.wikia.com/wiki/Category:Europe)\\n\\n- [New to reddit? click here!](/wiki/reddit_101)\\n\\n# Search AskEurope by flair\\n\\n||||\\n|--|--|--|\\n|[Serious](/r/AskEurope/search?q=flair%3ASerious&restrict_sr=on  \\\"Serious\\\")|[Culture](/r/AskEurope/search?q=flair%3ACulture&restrict_sr=on \\\"Culture\\\")|[Politics](/r/AskEurope/search?q=flair%3APolitics&restrict_sr=on \\\"Politics\\\")|\\n|[Law](/r/AskEurope/search?q=flair%3ALaw&restrict_sr=on \\\"Law\\\")|[History](/r/AskEurope/search?q=flair%3AHistory&restrict_sr=on \\\"History\\\")|[Work](/r/AskEurope/search?q=flair%3AWork&restrict_sr=on \\\"Work\\\")|\\n|[Travel](/r/AskEurope/search?q=flair%3ATravel&restrict_sr=on \\\"Travel\\\")|[Foreign](/r/AskEurope/search?q=flair%3AForeign&restrict_sr=on \\\"Foreign\\\")|[Misc](/r/AskEurope/search?q=flair%3AMisc&restrict_sr=on \\\"Misc\\\")|\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n# Europe-themed Subreddits:\\n\\n*  /r/Europe \\n\\n*  /r/europics \\n\\n*  /r/europeans \\n\\n* /r/europeanculture\\n\\n* /r/EuroDocs\\n\\n* /r/EuropeanFederalists\\n\\n* /r/Eurosceptics \\n\\n* /r/Interrail \\n\\n* /r/eulaw\\n\\n*  [List of European national and region subreddits](https://www.reddit.com/r/LocationReddits/wiki/faq/europe)\\n\\n# Ask a... subreddits\\n\\n* /r/AskAnAmerican\\n\\n* /r/AskACanadian\\n\\n* /r/AskanAustralian\\n\\n* /r/AskARussian\\n\\n* /r/FragReddit\\n\\n* /r/AskMENA\\n \", \"user_is_muted\": null, \"display_name\": \"AskEurope\", \"header_img\": \"https://d.thumbs.redditmedia.com/_-5zGESduEv9IG0Q.png\", \"title\": \"Ask Europe\", \"user_is_moderator\": null, \"over_18\": false, \"icon_size\": [256, 256], \"icon_img\": \"https://b.thumbs.redditmedia.com/QrWO8IQRgW0kuY7pTdmX2u7zs1ndumtk5qkjusMcTbg.png\", \"display_name_prefixed\": \"r/AskEurope\", \"header_size\": [124, 43], \"subscribers\": 15061, \"key_color\": \"#0079d3\", \"name\": \"t5_2uayg\", \"url\": \"/r/AskEurope/\", \"banner_size\": null, \"user_is_contributor\": null, \"public_description\": \"Ask Europe!\", \"subreddit_type\": \"public\", \"user_is_subscriber\": null}, \"can_gild\": false, \"thumbnail_height\": null, \"hide_score\": true, \"spoiler\": false, \"permalink\": \"/r/AskEurope/comments/6jzau9/hello_im_an_american_on_a_quest_to_find_out_how/?ref=search_posts\", \"num_reports\": null, \"locked\": false, \"stickied\": false, \"created\": 1498667946.0, \"url\": \"https://www.reddit.com/r/AskEurope/comments/6jzau9/hello_im_an_american_on_a_quest_to_find_out_how/\", \"author_flair_text\": null, \"quarantine\": false, \"title\": \"Hello. I'm an American on a quest to find out how healthcare works around the world. Let me ask the whole of Europe; what is healthcare like in your country?\", \"created_utc\": 1498639146.0, \"distinguished\": null, \"media\": null, \"num_comments\": 4, \"is_self\": true, \"visited\": false, \"subreddit_type\": \"public\", \"is_video\": false, \"ups\": 0}}], \"after\": \"t3_6jzau9\", \"before\": null}}"
    val fetcher = new TestFetcher(Map(
      Option("https://oauth.reddit.com/r/all/search.json") -> responseString,
      Option("https://www.reddit.com/api/v1/access_token")->"{\"access_token\":\"kaasZtJlZP-N0DKsGMr9cztURkM\",\"expires_in\":3600,\"scope\":\"*\",\"token_type\":\"bearer\"}"
    ))
    val client = new RedditClient("someAppId", "someAppSecret", fetcher = fetcher)
    client.ensureFreshToken()
    val objects = client.search(keywords = Seq("something"))
    assert(objects.nonEmpty)
  }

  it should "handle exceptions from malformed responses gracefully" in {
    val fetcher = new TestFetcher(Map(
      Option("https://oauth.reddit.com/r/all/search.json") -> "{badjson",
      Option("https://www.reddit.com/api/v1/access_token")->"{\"access_token\":\"kaasZtJlZP-N0DKsGMr9cztURkM\",\"expires_in\":3600,\"scope\":\"*\",\"token_type\":\"bearer\"}"
    ))
    val client = new RedditClient("someAppId", "someAppSecret", fetcher = fetcher)
    client.ensureFreshToken()
    val objects = client.search(keywords = Seq("something"))
    assert(objects.isEmpty)
  }

  it should "return an empty list when no search terms present" in {
    val fetcher = new TestFetcher(Map())
    val client = new RedditClient("someAppId", "someAppSecret", fetcher = fetcher)
    val objects = client.search(keywords = Seq())
    assert(objects.isEmpty)
  }

  it should "return an empty list when no token present" in {
    val fetcher = new TestFetcher(Map())
    val client = new RedditClient("someAppId", "someAppSecret", fetcher = fetcher)
    val objects = client.search(keywords = Seq("something"))
    assert(objects.isEmpty)
  }

} 
开发者ID:CatalystCode,项目名称:streaming-reddit,代码行数:59,代码来源:RedditClientSpec.scala

示例4: 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

示例5: PinterestApiClient

//设置package包名称以及导入依赖的类
package me.krobinson.mealplan

import scalaj.http.{HttpOptions, HttpRequest, Http}
import argonaut._, Argonaut._

import me.krobinson.mealplan.model._
import me.krobinson.mealplan.model.json._

import scalaz.{-\/, \/-}
import scalaz.syntax.id._

case class PinterestApiClient(at: AccessToken) {

  def buildPinterestApiRequest(path: String): HttpRequest = {
    val baseApi = "https://api.pinterest.com"
    Http(s"$baseApi/$path")
      .param("access_token", at.token)
      .param("limit", "100")
  }

  def request(path: String, params: Seq[(String, String)] = List.empty): HttpRequest = {
    buildPinterestApiRequest(path)
      .params(params)
      .option(HttpOptions.followRedirects(true))
  }

  def processResponse[A]
  (req: HttpRequest, target: String)
  (decoder: DecodeJson[ApiResponse[A]]): Result[A] = {
    val resp = req.asString
    if (resp.isNotError) {
      handleJson(resp.body.decode[ApiResponse[A]](decoder))(_.data)
    } else {
        s"""Failed to fetch $target:
          |
          |${resp.body}
          |
          |Are you sure that's a valid Pinterest board?
        """.stripMargin.left
    }
  }

  def getBoardMetadata(board: String): Result[Board] = {
    val req = request(s"v1/boards/$board", Seq(("fields", "url,id,name,counts,description")))
    processResponse(req, "board")(boardMetaCodec)
  }

  def getBoardPins(board: String): Result[List[Recipe]] = {
    // TODO use this to fetch more pins
    val numReqs = getBoardMetadata(board) match {
      case \/-(d) if d.counts.pins > 100 => Math.min(2, d.counts.pins / 100)
      case _ => 0
    }

    val req = request(s"v1/boards/$board/pins", Seq(("fields", "note,link,id,image,media,metadata")))
    processResponse[List[Recipe]](req, "pins")(boardPinsCodec)
  }
} 
开发者ID:robinske,项目名称:mealplanner,代码行数:59,代码来源:PinterestApiClient.scala

示例6: 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

示例7: UwdcConnector

//设置package包名称以及导入依赖的类
package org.kapunga.icelandic.connect

import java.io.{File, PrintWriter}

import org.kapunga.icelandic.util.md5

import scala.io.Source
import scala.util.Try
import scalaj.http.{Http, HttpRequest}


object UwdcConnector {
  val HEAD_URL: String = "http://digicoll.library.wisc.edu/cgi-bin/IcelOnline/IcelOnline.TEId-idx?"

  def fetchWord(word: String): String =
    fetch(Http(HEAD_URL)
      .param("type", "simple")
      .param("size", "First+100")
      .param("rgn", "lemma")
      .param("q1", word)
      .param("submit", "Search")
      .charset("ISO-8859-1"))

  def fetchFromFrag(urlFrag: String): String =
    fetch(urlFrag.split("\\?")(1)
      .split("&")
      .map(_.split("="))
      .foldLeft(Http(HEAD_URL))((u, p) => u.param(p(0), p(1)))
      .charset("ISO-8859-1"))

  def fetch(request: HttpRequest): String = {
    val urlHash = md5(request.urlBuilder(request))
    loadFromFile(urlHash).getOrElse(Try(cacheResponse(urlHash, request.asString.body)).getOrElse(request.asString.body))
  }

  def loadFromFile(urlHash: String): Option[String] =
    Try(Source.fromFile(cacheFileName(urlHash)).getLines()).map(_.toList.reduce((s1, s2) => s1 + "\n" + s2)).toOption

  def cacheResponse(urlHash: String, responseBody: String): String = {
    val file = new File(cacheFileName(urlHash))
    file.mkdirs()
    file.delete()
    file.createNewFile()

    val pw = new PrintWriter(file)
    pw.write(responseBody)
    pw.close()

    responseBody
  }

  def cacheFileName(urlHash: String): String = cacheDirectory + urlHash + ".txt"
} 
开发者ID:kapunga,项目名称:icelandic-sandbox,代码行数:54,代码来源:UwdcConnector.scala

示例8: WSubtask

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

import play.api.libs.json.{Json, Reads}

import scalaj.http.HttpRequest


case class WSubtask(
                   val id: Long,
                   val task_id: Long,
                   val created_at: String,
                   val created_by_id: Long,
                   val revision: Long,
                   val title: String
                   )

object WSubtask {
  implicit val listReads: Reads[WSubtask] = Json.reads[WSubtask]
  implicit def serializeRequest(req: HttpRequest): WSubtask = Json.parse(req.asString.body).as[WSubtask]
  implicit def serializeRequestList(req: HttpRequest): List[WSubtask] = Json.parse(req.asString.body).as[List[WSubtask]]
} 
开发者ID:hechen0,项目名称:wunderlist-scala,代码行数:22,代码来源:WSubtask.scala

示例9: Webhook

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

import play.api.libs.json.{Json, Reads}

import scalaj.http.HttpRequest


case class Webhook (
                     val id: Long,
                     val list_id: Long,
                     val membership_id: Long,
                     val membership_type: String,
                     val url: String,
                     val processor_type: String,
                     val configuration: String,
                     val created_at: String,
                     val updated_at: String
)

object Webhook {
  implicit val listReads: Reads[Webhook] = Json.reads[Webhook]
  implicit def serializeRequest(req: HttpRequest): Webhook = Json.parse(req.asString.body).as[Webhook]

} 
开发者ID:hechen0,项目名称:wunderlist-scala,代码行数:25,代码来源:Webhook.scala

示例10: WReminder

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

import play.api.libs.json.{Json, Reads}

import scalaj.http.HttpRequest


case class WReminder(
                    val id: Long,
                    val date: String,
                    val task_id: Long,
                    val revision: Long,
                    val `type`: String,
                    val created_at: String,
                    val updated_at: String
                    )

object WReminder {
  implicit val listReads: Reads[WReminder] = Json.reads[WReminder]
  implicit def serializeRequest(req: HttpRequest): WReminder = Json.parse(req.asString.body).as[WReminder]
  implicit def serializeRequestList(req: HttpRequest): List[WReminder] = Json.parse(req.asString.body).as[List[WReminder]]
} 
开发者ID:hechen0,项目名称:wunderlist-scala,代码行数:23,代码来源:WReminder.scala

示例11: WAvatar

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

import play.api.libs.json.{Json, Reads}

import scalaj.http.HttpRequest


case class WAvatar(
  val url: String,
  val size: String
)

object WAvatar {
  implicit val listReads: Reads[WAvatar] = Json.reads[WAvatar]
  implicit def serializeRequest(req: HttpRequest): WAvatar = {
    Json.parse(req.asString.body).as[WAvatar]
  }
} 
开发者ID:hechen0,项目名称:wunderlist-scala,代码行数:19,代码来源:WAvatar.scala

示例12: WUser

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

import play.api.libs.json.{Json, Reads}

import scalaj.http.HttpRequest

case class WUser(
  val id: Long,
  val name: String,
  val email: String,
  val created_at: String,
  val revision: Long
)

object WUser {
  implicit val listReads: Reads[WUser] = Json.reads[WUser]
  implicit def serializeRequest(req: HttpRequest): WUser = Json.parse(req.asString.body).as[WUser]
  implicit def serializeRequestList(req: HttpRequest): List[WUser] = Json.parse(req.asString.body).as[List[WUser]]
} 
开发者ID:hechen0,项目名称:wunderlist-scala,代码行数:20,代码来源:WUser.scala

示例13: WFolderRevision

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

import play.api.libs.json.{Json, Reads}

import scalaj.http.HttpRequest

case class WFolderRevision(
  val id: Long,
  val `type`: String,
  val revision: Long
)

object WFolderRevision {
  implicit val listReads: Reads[WFolderRevision] = Json.reads[WFolderRevision]
  implicit def serializeRequest(req: HttpRequest): WFolderRevision =
    Json.parse(req.asString.body).as[WFolderRevision]
  implicit def serializeRequestList(req: HttpRequest): List[WFolderRevision] =
    Json.parse(req.asString.body).as[List[WFolderRevision]]
} 
开发者ID:hechen0,项目名称:wunderlist-scala,代码行数:20,代码来源:WFolderRevision.scala

示例14: WList

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

import com.hechen0.wunderlist_scala.Request
import play.api.libs.json._

import scalaj.http.HttpRequest

case class WList (
  val id: Long,
  val created_at: String,
  val title: String,
  val list_type: String,
  val `type`: String,
  val revision: Long
)

object WList {
  implicit val listReads: Reads[WList] = Json.reads[WList]
  implicit def serializeRequest(req: HttpRequest): WList = Json.parse(req.asString.body).as[WList]
  implicit def serializeRequestList(req: HttpRequest): List[WList] = Json.parse(req.asString.body).as[List[WList]]
} 
开发者ID:hechen0,项目名称:wunderlist-scala,代码行数:22,代码来源:WList.scala

示例15: WFolder

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

import play.api.libs.json.{Json, Reads}

import scalaj.http.HttpRequest

case class WFolder(
  val id: Long,
  val title: String,
  val list_ids: List[Long],
  val `type`: String,
  val revision: Long
)

object WFolder {
  implicit val listReads: Reads[WFolder] = Json.reads[WFolder]
  implicit def serializeRequest(req: HttpRequest): WFolder = Json.parse(req.asString.body).as[WFolder]
  implicit def serializeRequestList(req: HttpRequest): List[WFolder] = Json.parse(req.asString.body).as[List[WFolder]]
} 
开发者ID:hechen0,项目名称:wunderlist-scala,代码行数:20,代码来源:WFolder.scala


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