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

Scala URLEncoder类代码示例

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

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



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

示例1: RequestNormalization

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

import java.nio.charset.StandardCharsets
import java.util.UUID
import java.net.URLEncoder
import com.twitter.finagle.http.Request
import shapeless.tag._
import cats.implicits._
import com.lookout.ratelimitingfilter.models._


object RequestNormalization {
  def apply(
    serviceLookup: Request => Option[String @@ ServiceName],
    claimLookup: Request => Option[(UUID @@ EntClaim, UUID @@ SubClaim)],
    request: Request
  ): List[String] = {
    val method = request.method
    val path = encodePath(request.path)
    val serviceBuckets: Option[List[String]] = serviceLookup(request).map {
      serviceName => s"$method::$serviceName" :: s"$method::$path::$serviceName" :: Nil
    }
    val idBuckets: Option[List[String]] = claimLookup(request).map {
      case (entUuid, subUuid) =>
        s"$method::$path::$entUuid" :: s"$method::$path::$subUuid" :: Nil
    }

    (serviceBuckets |+| idBuckets).getOrElse(Nil)
  }

  def encodePath(path: String): String =
    URLEncoder.encode(path, StandardCharsets.UTF_8.toString).toLowerCase
} 
开发者ID:lookout,项目名称:rate-limiting-strategy,代码行数:34,代码来源:RequestNormalization.scala


示例2: MCWhitelistHelper

//设置package包名称以及导入依赖的类
package com.amadornes.modcast.bot.helpers

import java.net.URLEncoder

import com.amadornes.modcast.bot.Actors
import com.amadornes.modcast.bot.database.{DB, UserMCAccount}
import com.amadornes.modcast.bot.servers.MCWhitelistServer
import com.google.gson.{Gson, JsonObject}
import sx.blah.discord.handle.obj.IUser

import scalaj.http.Http


object MCWhitelistHelper {
	def associateMCAccountWithUser(user: IUser, account: String): Unit = {
		val id = getMCAccountUUID(account)
		if (DB.query[UserMCAccount].whereEqual("user", user.getID).exists())
			deassociateMCAccountWithUser(user)
		Actors.servers.MCWhitelistServer ! MCWhitelistServer.WhitelistUser(id)
		DB.save(UserMCAccount(user.getID, id))
	}
	
	def deassociateMCAccountWithUser(user: IUser): Unit = {
		val account = DB.query[UserMCAccount].whereEqual("user", user.getID).fetchOne()
		if (account.isDefined) {
			Actors.servers.MCWhitelistServer ! MCWhitelistServer.UnWhitelistUser(account.get.account)
			DB.delete(account.get)
		}
	}
	
	def getMCAccountUUID(name: String): String = {
		val http = Http("http://mcapi.ca/profile/" + URLEncoder.encode(name)).asString
		if (http.code != 200)
			throw new IllegalArgumentException()
		new Gson().fromJson(http.body, classOf[JsonObject]).get("uuid_formatted").getAsString
	}
} 
开发者ID:Modcast,项目名称:ModcastBot,代码行数:38,代码来源:MCWhitelistHelper.scala


示例3: TempasWaybackSpec

//设置package包名称以及导入依赖的类
package de.l3s.archivespark.specific.warc.tempas

import java.net.URLEncoder

import de.l3s.archivespark.dataspecs.DataSpec
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.HttpClients
import org.apache.spark.SparkContext
import org.apache.spark.rdd.RDD

import scala.io.Source

class TempasWaybackSpec private (query: String, from: Option[Int] = None, to: Option[Int] = None, pages: Int, resultsPerPage: Int) extends DataSpec[TempasYearResult, TempasWaybackRecord] {
  import TempasWaybackSpec._

  def searchUrl(page: Int): String = {
    val queryEncoded = URLEncoder.encode(query, "UTF-8")
    var url = TempasSearchUrl.replace("$r", resultsPerPage.toString).replace("$p", page.toString).replace("$q", queryEncoded)
    if (from.isDefined) url += "&from=" + from.get
    if (to.isDefined) url += "&to=" + to.get
    url
  }

  override def load(sc: SparkContext, minPartitions: Int): RDD[TempasYearResult] = {
    sc.parallelize(1 to pages, minPartitions).flatMap { page =>
      @transient val client = HttpClients.createDefault
      @transient val get = new HttpGet(searchUrl(page))
      get.setHeader("Accept", AcceptType)
      val in = client.execute(get).getEntity.getContent
      try {
        Source.fromInputStream(in).getLines().toList.flatMap { line =>
          TempasYearResult.resultsFromTsv(line)
        }
      } finally {
        in.close()
      }
    }.repartition(minPartitions)
  }

  override def parse(result: TempasYearResult): Option[TempasWaybackRecord] = {
    Some(new TempasWaybackRecord(result))
  }
}

object TempasWaybackSpec {
  val TempasSearchUrl = "http://tempas.l3s.de/v2/query?resultsPerPage=$r&page=$p&q=$q"
  val DefaultResultsPerPage = 100
  val DefaultPages = 100
  val AcceptType = "text/tab-separated-values"

  def apply(query: String, from: Int = -1, to: Int = -1, pages: Int = DefaultPages, resultsPerPage: Int = DefaultResultsPerPage): TempasWaybackSpec = {
    val fromOpt = if (from < 0) None else Some(from)
    val toOpt = if (to < 0) None else Some(to)
    new TempasWaybackSpec(query, fromOpt, toOpt, pages, resultsPerPage)
  }
} 
开发者ID:helgeho,项目名称:Tempas2ArchiveSpark,代码行数:57,代码来源:TempasWaybackSpec.scala


示例4: lurlEncode

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

import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF
import java.net.URLEncoder

@Description(
        name = "lurlEncode",
        value = "_FUNC_(string) URLEncode - encodes a string into application/x-www-form-urlencoded type (UTF-8)",
        extended = "SELECT lurlEncode(url) FROM test LIMIT 1;")
class lurlEncode extends UDF {
  def evaluate(url: String ): String= {
	if (url == null )
	   return null
	val encodedURL= java.net.URLEncoder.encode(url, "UTF-8");
	return (encodedURL)
	
  }

} 
开发者ID:lserinol,项目名称:Hive-udfs,代码行数:21,代码来源:lurlencode.scala


示例5: RelativeActorPathSpec

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

import org.scalatest.WordSpec
import org.scalatest.Matchers
import java.net.URLEncoder
import scala.collection.immutable

class RelativeActorPathSpec extends WordSpec with Matchers {

  def elements(path: String): immutable.Seq[String] = RelativeActorPath.unapply(path).getOrElse(Nil)

  "RelativeActorPath" must {
    "match single name" in {
      elements("foo") should be(List("foo"))
    }
    "match path separated names" in {
      elements("foo/bar/baz") should be(List("foo", "bar", "baz"))
    }
    "match url encoded name" in {
      val name = URLEncoder.encode("akka://[email protected]:2552", "UTF-8")
      elements(name) should be(List(name))
    }
    "match path with uid fragment" in {
      elements("foo/bar/baz#1234") should be(List("foo", "bar", "baz#1234"))
    }
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:28,代码来源:RelativeActorPathSpec.scala


示例6: CanonicalRequest

//设置package包名称以及导入依赖的类
package akka.stream.alpakka.s3.auth

import java.net.URLEncoder

import akka.http.scaladsl.model.Uri.{Path, Query}
import akka.http.scaladsl.model.{HttpHeader, HttpRequest}

// Documentation: http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
private[alpakka] case class CanonicalRequest(method: String,
                                             uri: String,
                                             queryString: String,
                                             headerString: String,
                                             signedHeaders: String,
                                             hashedPayload: String) {
  def canonicalString: String = s"$method\n$uri\n$queryString\n$headerString\n\n$signedHeaders\n$hashedPayload"
}

private[alpakka] object CanonicalRequest {
  def from(req: HttpRequest): CanonicalRequest = {
    val hashedBody = req.headers.find(_.name == "x-amz-content-sha256").map(_.value).getOrElse("")
    CanonicalRequest(
      req.method.value,
      pathEncode(req.uri.path),
      canonicalQueryString(req.uri.query()),
      canonicalHeaderString(req.headers),
      signedHeadersString(req.headers),
      hashedBody
    )
  }

  def canonicalQueryString(query: Query): String =
    query.sortBy(_._1).map { case (a, b) => s"${uriEncode(a)}=${uriEncode(b)}" }.mkString("&")

  private def uriEncode(str: String) = URLEncoder.encode(str, "utf-8")

  def canonicalHeaderString(headers: Seq[HttpHeader]): String = {
    val grouped = headers.groupBy(_.lowercaseName())
    val combined = grouped.mapValues(_.map(_.value.replaceAll("\\s+", " ").trim).mkString(","))
    combined.toList.sortBy(_._1).map { case (k, v) => s"$k:$v" }.mkString("\n")
  }

  def signedHeadersString(headers: Seq[HttpHeader]): String =
    headers.map(_.lowercaseName()).distinct.sorted.mkString(";")

  private def pathEncode(path: Path): String =
    if (path.isEmpty) "/"
    else
      path.toString().flatMap {
        case ch if "!$&'()*+,;:=".contains(ch) => "%" + Integer.toHexString(ch.toInt).toUpperCase
        case other => other.toString
      }

} 
开发者ID:akka,项目名称:alpakka,代码行数:54,代码来源:CanonicalRequest.scala


示例7: CanonicalRequest

//设置package包名称以及导入依赖的类
package edu.goldlok.minio_scala.auth

import akka.http.scaladsl.model.{HttpHeader, HttpRequest}
import akka.http.scaladsl.model.Uri.{Path, Query}

import java.net.URLEncoder



case class CanonicalRequest(method: String, uri: String,
                            queryString: String,
                            headerString: String,
                            signedHeaders: String,
                            hashedPayload: String) {
  def canonicalString: String = {
    s"$method\n$uri\n$queryString\n$headerString\n\n$signedHeaders\n$hashedPayload"
  }
}

object CanonicalRequest {
  private[this] val content_sha256 = "x-amz-content-sha256"
  def from(req: HttpRequest): CanonicalRequest = {
    val hashedBody = req.headers.find(_.name == content_sha256).map(_.value).getOrElse("")
    CanonicalRequest(
      req.method.value,
      preprocessPath(req.uri.path),
      canonicalQueryString(req.uri.query()),
      canonicalHeaderString(req.headers),
      signedHeadersString(req.headers),
      hashedBody
    )
  }

  def canonicalQueryString(query: Query): String = {
    query.sortBy(_._1).map { case (a, b) => s"${uriEncode(a)}=${uriEncode(b)}" }.mkString("&")
  }

  def uriEncode(str: String): String = URLEncoder.encode(str, "utf-8")

  def preprocessPath(path: Path): String = {
    uriEncode(path.toString()).replace(":", "%3A").replace("%2F", "/")
  }

  def canonicalHeaderString(headers: Seq[HttpHeader]): String = {
    val grouped = headers.groupBy(_.lowercaseName())
    val combined = grouped.mapValues(_.map(_.value.replaceAll("\\s+", " ").trim).mkString(","))
    combined.toList.sortBy(_._1).map { case (k, v) => s"$k:$v" }.mkString("\n")
  }

  def signedHeadersString(headers: Seq[HttpHeader]): String = {
    headers.map(_.lowercaseName()).distinct.sorted.mkString(";")
  }
} 
开发者ID:TopSpoofer,项目名称:minio-scala,代码行数:54,代码来源:CanonicalRequest.scala


示例8: valueStream

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

import java.net.URLEncoder
import java.util.Date

import com.zhranklin.homepage.blog.Article

import scala.util.Try

trait IndexService {
  protected val template: String
  protected val firstIndex: Int = 1
  protected def valueStream(i: Int): Stream[Int] = i #:: valueStream(i + 1)
  protected def indexNums: Iterable[Any] = valueStream(firstIndex)
  protected def interpolate(value: Any): String = template.replaceAll("<index>", value.toString)
  def indexUrls: Iterable[String] = indexNums map interpolate
}

case class Notice(url: String, title: String, html: String, date: Date)
case class NoticeEntry(url: String, title: Option[String] = None)

abstract class NoticeService(val source: String) extends UrlService with IndexService with NoticeFetcher {
  def getUrls: Iterable[NoticeEntry] = indexUrls.map(u ? Try(noticeUrlsFromUrl(u))).takeWhile(_.isSuccess).flatMap(_.get)
  def notices(after: Date = new Date(0)): Iterable[Notice] = getUrls.map(n ? Try(fetch(n))).filter(_.isSuccess).take(30).map(_.get).takeWhile(_.date.after(after))
  def toArticle(notice: Notice) = new Article(notice.title, source, "notice", None, notice.html, "", Nil, notice.date) {
    override val itemLink = s"/notice/$source?url=" + URLEncoder.encode(notice.url, "utf-8")
  }
} 
开发者ID:zhranklin,项目名称:Private_Blog,代码行数:29,代码来源:NoticeService.scala


示例9: URIUtils

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

import java.net.{URI, URLEncoder}

import com.google.common.base.Charsets
import play.utils.UriEncoding

object URIUtils {
  private val sep = "/"

  def appendPath(uri: URI, path: String): URI = {
    val encodedPath = UriEncoding.encodePathSegment(path.stripPrefix(sep), Charsets.UTF_8.name())
    new URI(uri.toString.stripSuffix(sep) + sep + encodedPath)
  }

  def appendQuery(uri: URI, qs: (String, String)*): URI =
    new URI(uri.toString + queryToString(qs:_*))

  def queryToString(qs: (String, String)*): String =
    qs.map { case(k, v) =>
      k + "=" + URLEncoder.encode(v, Charsets.UTF_8.name()).replaceAll(" ", "%20")
    }.mkString(if (qs.isEmpty) "" else "?", "&", "")
} 
开发者ID:pygmalios,项目名称:reactiveinflux,代码行数:24,代码来源:URIUtils.scala


示例10: RemoteBot

//设置package包名称以及导入依赖的类
package im.actor.botkit

import java.net.URLEncoder

import akka.stream.scaladsl.{ Sink, Source }
import akka.stream.{ ActorMaterializer, OverflowStrategy }
import akka.util.Timeout
import im.actor.bots.BotMessages
import im.actor.concurrent.ActorFutures
import upickle.default._

import scala.concurrent.duration._

object RemoteBot {
  val DefaultEndpoint = "wss://api.actor.im"

  private object StreamComplete
}

abstract class RemoteBot(token: String, endpoint: String) extends BotBase with ActorFutures {

  import BotMessages._
  import RemoteBot._

  override protected implicit val timeout: Timeout = Timeout(30.seconds)
  private implicit val mat = ActorMaterializer()

  initFlow()

  def onReceive(message: Object): Unit = {}

  def receive: Receive = internalReceive orElse {
    case message ?
      onReceive(message.asInstanceOf[Object])
  }

  override protected def onStreamFailure(cause: Throwable): Unit = {
    log.error(cause, "Stream failure")
    initFlow()
  }

  private final def internalReceive: Receive = workingBehavior.orElse({
    case StreamComplete ?
      log.warning("Disconnected, reinitiating flow")
      initFlow()
  })

  private def initFlow(): Unit = {
    val (wsSource, wsSink) = WebsocketClient.sourceAndSink(s"$endpoint/v1/bots/${URLEncoder.encode(token, "UTF-8")}")

    wsSource.map(read[BotMessageOut]).to(Sink.actorRef(self, StreamComplete)).run()

    val rqSource = Source.actorRef(bufferSize = 100, overflowStrategy = OverflowStrategy.fail)
      .map(write[BotRequest])
      .to(wsSink)
      .run()

    setRqSource(rqSource)
  }
} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:61,代码来源:RemoteBot.scala


示例11: signRequest

//设置package包名称以及导入依赖的类
package im.actor.server.file.local

import java.net.URLEncoder

import akka.actor.ActorSystem
import akka.http.scaladsl.model.{ HttpMethod, Uri }
import im.actor.acl.ACLBase
import org.apache.commons.codec.digest.DigestUtils.sha256Hex
import org.apache.commons.codec.digest.HmacUtils

trait RequestSigning extends ACLBase {

  private val urlEncode: String ? String = URLEncoder.encode(_, "UTF-8")

  def signRequest(httpVerb: HttpMethod, uri: Uri, secret: String): Uri =
    uri.withQuery(("signature" ? calculateSignature(httpVerb, uri, secret)) +: uri.query())

  def calculateSignature(httpVerb: HttpMethod, uri: Uri)(implicit system: ActorSystem): String =
    calculateSignature(httpVerb, uri, secretKey())

  def calculateSignature(httpVerb: HttpMethod, uri: Uri, secret: String): String = {
    val resourcePath = uri.path
    val canonicalQueryString = uri.query() sortBy (_._1) map {
      case (name, value) ?
        s"${urlEncode(name)}=${urlEncode(value)}"
    } mkString "&"

    val canonicalRequest =
      s"""$httpVerb
         |$resourcePath
         |$canonicalQueryString""".stripMargin

    HmacUtils.hmacSha256Hex(secret, sha256Hex(canonicalRequest))
  }
} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:36,代码来源:RequestSigning.scala


示例12: MovieNameToIMDBPipeline

//设置package包名称以及导入依赖的类
package com.stacktrace.yo.scrapeline.imdb.pipelines

import java.net.URLEncoder
import java.nio.file.Paths

import akka.stream.scaladsl.{FileIO, Flow, Framing, Source}
import akka.stream.{ActorMaterializer, IOResult}
import akka.util.ByteString
import akka.{Done, NotUsed}
import com.stacktrace.yo.scrapeline.imdb.Domain.MovieNameAndDetailUrl

import scala.concurrent.{ExecutionContext, Future}

class MovieNameToIMDBPipeline(implicit val m: ActorMaterializer, implicit val ec: ExecutionContext) {

  private def getPipelineSource: Source[String, Future[IOResult]] = {
    FileIO.fromPath(Paths.get("movie.txt"))
      .via(Framing.delimiter(ByteString("\n"), 256)
        .map(_.utf8String)
      )
  }

  private def getDetailUrlFlow: Flow[String, MovieNameAndDetailUrl, NotUsed] = {
    Flow[String]
      .mapAsyncUnordered(100)(mapPipeToImdbSearch)
  }


  private def mapPipeToImdbSearch(in: String): Future[MovieNameAndDetailUrl] = Future {
    val encodedString: String = URLEncoder.encode(in, "UTF-8")
    MovieNameAndDetailUrl(in, "http://www.imdb.com/find?ref_=nv_sr_fn&q=" + encodedString + "&s=tt")
  }


  def getOutput: Future[Done] = {
    getPipelineSource
      .via(getDetailUrlFlow)
      .via(new IMDBSearchSubPipe().getSubFlow)
      .runForeach(x => println(x.name + ":" + x.url))
  }

} 
开发者ID:StackTraceYo,项目名称:scrapeline,代码行数:43,代码来源:MovieNameToIMDBPipeline.scala


示例13: Config

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

import java.net.URLEncoder

import com.catinthedark.common.Const

object Config {
  val pb = new ProcessBuilder()

  def gameTick: Int = try {
      pb.environment().getOrDefault("GAME_TICK", Const.Networking.tickDelay.toString).toInt
    } catch {
      case e: Exception => Const.Networking.tickDelay
    }

  def port: Int = try {
      pb.environment().getOrDefault("PORT", "9000").toInt
    } catch {
      case e: Exception => 9000
    }

  def notificationURL(message: String): String = {
    val key = pb.environment.get("TELEGRAM_KEY")
    val chatId = pb.environment.get("TELEGRAM_CHAT_ID")
    val msg = URLEncoder.encode(message, "UTF-8")
    s"https://api.telegram.org/bot$key/sendMessage?chat_id=$chatId&disable_web_page_preview=1&text=$msg"
  }

  def jdbcUser = pb.environment().getOrDefault("JDBC_DATABASE_USERNAME", "postgres")
  def jdbcPassword = pb.environment().getOrDefault("JDBC_DATABASE_PASSWORD", "")
  def jdbcURL = pb.environment().getOrDefault("JDBC_DATABASE_URL", "jdbc:postgresql://localhost:5432/postgres")
} 
开发者ID:cat-in-the-dark,项目名称:old48_36_game,代码行数:33,代码来源:Config.scala


示例14: PlainQueryConverter

//设置package包名称以及导入依赖的类
package com.hypertino.hyperbus.model.hrl

import java.net.{URLDecoder, URLEncoder}

import com.hypertino.binders.value.{Null, Obj, Text, Value}

object PlainQueryConverter extends QueryConverter {
  final val encoding = "UTF-8"

  override def parseQueryString(queryString: String): Value = {
    if (queryString == null || queryString.isEmpty) {
      Null
    } else {

      Obj(queryString.split('&').map { s ?
        val i = s.indexOf('=')
        if (i>0) {
          val left = s.substring(0, i)
          val right = Text(URLDecoder.decode(s.substring(i+1), encoding))
          left ? right
        }
        else {
          s ? Null
        }
      }.toMap)
    }
  }

  override def toQueryString(value: Value): String = {
    value match {
      case Null ? ""
      case Text(s) ? s
      case Obj(elements) ? elements.map { case (k, v) ?
        if (v.isNull) {
          k
        }
        else {
          k + "=" + URLEncoder.encode(v.toString, encoding)
        }
      } mkString "&"
      case other ? throw new IllegalArgumentException(s"$other is not an Obj or Text")
    }
  }
} 
开发者ID:hypertino,项目名称:hyperbus,代码行数:45,代码来源:PlainQueryConverter.scala


示例15: queryStringLocalDateBinder

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

import java.text.SimpleDateFormat
import java.util.Date

import play.api.mvc.QueryStringBindable

trait DateBinders {
  implicit def queryStringLocalDateBinder = new QueryStringBindable[Date] {

    val format = "yyyyMMdd"

    override def bind(key: String, params: Map[String, Seq[String]]): Option[Either[String, Date]] = {
      params(key).headOption map { dateString =>
        try {
          val sdf = new SimpleDateFormat(format)
          Right(sdf.parse(dateString))
        } catch {
          case e: IllegalArgumentException => Left("Failed to parse query string as Date.")
        }
      }
    }
    override def unbind(key: String, date: Date): String = {
      import java.net.URLEncoder
      URLEncoder.encode(key, "utf-8") + "&" + URLEncoder.encode(date.toString, "utf-8")
    }
  }
}

object Binders extends DateBinders 
开发者ID:takat0-h0rikosh1,项目名称:play_boilerplate,代码行数:31,代码来源:Binders.scala


示例16: MovieService

//设置package包名称以及导入依赖的类
package fi.kajstrom.efpscala.E50

import java.net.URLEncoder

class MovieService {
  def findByName(name: String): Movie = {
    val urlEncodedName = URLEncoder.encode(name, "UTF-8")
    //println(retrieveMovieJSON(urlEncodedName))

    //Return dummy data as Rotten Tomatoes API shows my user account as inactive still.
    Movie("The Movie", 2017, "PG-13", 120, "Dummy movie to implement the CLI part of the application as " +
      "the API is not working for me yet...")
  }

  private def retrieveMovieJSON(query: String): String = {
    import java.net.{URL, HttpURLConnection}
    val connection = new URL(s"http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=mg8jqzehw3jj52shbv8uj2bg&q=$query&page_limit=1&page=1").openConnection.asInstanceOf[HttpURLConnection]

    connection.setConnectTimeout(3000)
    connection.setReadTimeout(3000)
    connection.setRequestMethod("GET")

    val inputStream = connection.getInputStream
    val content = scala.io.Source.fromInputStream(inputStream).mkString

    if (inputStream != null) inputStream.close()

    content
  }
}

case class Movie(title: String, year: Int, rating: String, runningTime: Int, desc: String) 
开发者ID:kajstrom,项目名称:EFP-Scala,代码行数:33,代码来源:MovieService.scala


示例17: ComicsController

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

import java.net.URLEncoder
import javax.inject._

import play.api.mvc._
import services.{Comic, ComicRepo}
import scalatags.Text.all._


@Singleton
class ComicsController @Inject()(comicRepo: ComicRepo) extends Controller {

  def index = Action { implicit request =>
    Ok(views.html.comics(comicRepo.getComics().map(ComicWithShare(_))))
  }

  def show(slug: String) = {
    comicRepo.findOneWithSlug(slug) match {
      case Some(comic) => showComic(comic)
      case None => Action { Redirect("/") }
    }
  }

  def showComic(comic: Comic) = Action { implicit request =>
    val title = s"${comic.artist} - ${comic.title}"
    val next = comicRepo.findNextComic(comic,  1).map(c => routes.ComicsController.show(c.slug)).getOrElse(routes.ComicsController.index())
    val prev = comicRepo.findNextComic(comic, -1).map(c => routes.ComicsController.show(c.slug)).getOrElse(routes.ComicsController.index())
    Ok(views.html.comic(ComicWithShare(comic), title, next, prev))
  }
}

case class ComicWithShare(comic: Comic)(implicit request: Request[AnyContent]) {
  val facebookSharer: String = {
    val url = URLEncoder.encode(routes.ComicsController.show(comic.slug).absoluteURL(), "UTF-8")
    s"https://www.facebook.com/sharer/sharer.php?u=$url"
  }

  val twitterSharer: String = {
    val text = URLEncoder.encode(s"${comic.artist} - ${comic.title}", "UTF-8")
    val url = URLEncoder.encode(routes.ComicsController.show(comic.slug).absoluteURL(), "UTF-8")
    s"https://twitter.com/intent/tweet?text=$text&url=$url"
  }
} 
开发者ID:eckyputrady,项目名称:comicaze,代码行数:45,代码来源:ComicsController.scala


示例18: DaumCook

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

import java.net.URLEncoder
import java.util.Calendar


import models.{Photo, MessageButton, Message}
import play.api.Logger
import utils.HtmlParser

import scala.util.Random

object DaumCook {
    val KEY_SEARCH = "\uD83C\uDF7D ?? ????"
    val KEY_TODAY = "\uD83C\uDF72 ?? ? ????"
    val KEY_TIP = "??? ???"
    type JDoc = org.jsoup.nodes.Document
    def recommendRecipe(): Message ={
        val cal:Calendar = Calendar.getInstance()

        val links = List(
            "http://m.cook.miznet.daum.net/ranking/bestrecipe/rankingRecipeList?rankType=1&datekey=3",
            "http://m.cook.miznet.daum.net/ranking/scraprecipe/rankingRecipeList?rankType=8",
            "http://m.cook.miznet.daum.net/ranking/bestrecipe/rankingRecipeList?rankType=1&datekey=2",
            "http://m.cook.miznet.daum.net/ranking/hitrecipe/rankingRecipeList?rankType=2",
            "http://m.cook.miznet.daum.net/ranking/hitrecipe/rankingRecipeList?rankType=3",
            "http://m.cook.miznet.daum.net/ranking/hitrecipe/rankingRecipeList?rankType=4",
            "http://m.cook.miznet.daum.net/ranking/hitrecipe/rankingRecipeList?rankType=5",
            "http://m.cook.miznet.daum.net/ranking/hitrecipe/rankingRecipeList?rankType=6",
            "http://m.cook.miznet.daum.net/calendar/list?type=D",
            s"http://m.cook.miznet.daum.net/search?q=${cal.get(Calendar.MONTH)}%EC%9B%94",
            "http://m.cook.miznet.daum.net/ranking/bestrecipe/rankingRecipeList?rankType=1&datekey=1"
        )
        val url = Random.shuffle(links).last
        val doc = HtmlParser.get(url)
        val list = HtmlParser.linkSequence(doc,"cook/recipe/read")
        Logger.info(s"url : ${url} , result size : ${list.size}")
        val idx:Int = Random.shuffle(0 to list.size-1).toSeq.last
        val images = doc.body.toString.split("\n").filter(_.indexOf("Rank.addUrl") > 0)
        val selected = list(idx)
        val src = images.size match {
            case 0 => selected.imageSrc
            case _ => images(idx).replace("\tRank.addUrl(\"\t\t","").replace("\");","")
        }
        val reg = "^[0-9]+".r
        Message(reg.replaceFirstIn(selected.title,"").trim, Option(Photo(src,140,101)), Option(MessageButton("??? ??",selected.href)))
    }
    def searchRecipe(keyword: String): Message ={
        val link =s"http://m.cook.miznet.daum.net/search?q=${URLEncoder.encode(keyword,"UTF-8")}"
        val text:String = HtmlParser.linkSequence(HtmlParser.get(link),"cook/recipe/read").map{doc =>
            s"${doc.title} (${doc.desc})\n-${doc.href}"
        }.mkString("\n")
        Message(text)
    }

}

case class DaumCook(title: String, link: String, thumbnail: String) 
开发者ID:suya55,项目名称:kakaoYellowIdBot,代码行数:59,代码来源:DaumCook.scala


示例19: StandardSolrSearchSpec

//设置package包名称以及导入依赖的类
package org.nlp4l.framework.builtin

import java.net.URLEncoder

import org.nlp4l.framework.models.CellType
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification

class StandardSolrSearchSpec extends Specification with Mockito {

  val searchOn = "http://localhost:8983/solr"
  def cellAtt(separatedBy: String, hlField: String = null) = new StandardSolrSearchCellAttribute(searchOn, "collection1", "id", hlField, separatedBy, "cell1", CellType.StringType, true, false)

  "StandardSolrSearchCellAttribute" should {
    "format cell value with a separator" in {
      val mockCell = mock[Any]
      mockCell.toString() returns "???,???,??????"

      val expected =
        List(
          s"""<a href="/searchResult/solr/${URLEncoder.encode(searchOn, "UTF-8")}/collection1/${URLEncoder.encode("???", "UTF-8")}?id=id">???</a>""",
          s"""<a href="/searchResult/solr/${URLEncoder.encode(searchOn, "UTF-8")}/collection1/${URLEncoder.encode("???", "UTF-8")}?id=id">???</a>""",
          s"""<a href="/searchResult/solr/${URLEncoder.encode(searchOn, "UTF-8")}/collection1/${URLEncoder.encode("??????", "UTF-8")}?id=id">??????</a>"""
        ).mkString(",")
      cellAtt(",").format(mockCell) mustEqual expected
    }

    "format cell value with multiple separators" in {
      val mockCell = mock[Any]
      mockCell.toString() returns "???,??? => ??????"

      val expected =
        List(
          s"""<a href="/searchResult/solr/${URLEncoder.encode(searchOn, "UTF-8")}/collection1/${URLEncoder.encode("???", "UTF-8")}?id=id">???</a>""",
          s"""<a href="/searchResult/solr/${URLEncoder.encode(searchOn, "UTF-8")}/collection1/${URLEncoder.encode("???", "UTF-8")}?id=id">???</a>"""
        ).mkString(",") +
          " => " + s"""<a href="/searchResult/solr/${URLEncoder.encode(searchOn, "UTF-8")}/collection1/${URLEncoder.encode("??????", "UTF-8")}?id=id">??????</a>"""
      cellAtt("(,)|(=>)").format(mockCell) mustEqual expected
    }

    "return empty string when cell value is empty" in {
      val mockCell = mock[Any]
      mockCell.toString() returns ""
      cellAtt(",").format(mockCell) mustEqual ""
    }

    "format cell value with highlight" in {
      val mockCell = mock[Any]
      mockCell.toString() returns "???,???,??????"

      val expected =
        List(
          s"""<a href="/searchResult/solr/${URLEncoder.encode(searchOn, "UTF-8")}/collection1/${URLEncoder.encode("???", "UTF-8")}?id=id&hl=body">???</a>""",
          s"""<a href="/searchResult/solr/${URLEncoder.encode(searchOn, "UTF-8")}/collection1/${URLEncoder.encode("???", "UTF-8")}?id=id&hl=body">???</a>""",
          s"""<a href="/searchResult/solr/${URLEncoder.encode(searchOn, "UTF-8")}/collection1/${URLEncoder.encode("??????", "UTF-8")}?id=id&hl=body">??????</a>"""
        ).mkString(",")
      cellAtt(",", "body").format(mockCell) mustEqual expected
    }

  }
} 
开发者ID:NLP4L,项目名称:nlp4l,代码行数:62,代码来源:StandardSolrSearchSpec.scala


示例20:

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

import java.net.URLEncoder

trait HasQueryParameters { self: HasParameters =>

  val queryParameters = {
    val sb = new StringBuilder()
    val qs = parameters.foldLeft(sb) {
      case (agg, (key, value)) =>
        if (Option(value).isDefined) {
          agg.append(key)
            .append("=")
            .append(URLEncoder.encode(value.toString, "UTF-8"))
            .append("&")
        } else {
          agg
        }
    }.toString()

    if (qs.isEmpty) qs else qs.init
  }
} 
开发者ID:amarjanica,项目名称:discourse-scala-client,代码行数:24,代码来源:HasQueryParameters.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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