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

Scala HttpURLConnection类代码示例

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

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



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

示例1: CustomerController

//设置package包名称以及导入依赖的类
package fr.sysf.sample.service


import java.net.HttpURLConnection
import javax.validation.Valid

import fr.sysf.sample.domain.Customer
import io.swagger.annotations.{Api, ApiOperation, ApiResponse, ApiResponses}
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.{HttpStatus, MediaType, ResponseEntity}
import org.springframework.web.bind.annotation._


@Api(value = "Customers service", consumes = "application/json;charset=UTF-8", produces = "application/json;charset=UTF-8")
@RestController
@RequestMapping(Array("/customers"))
class CustomerController {

  @Autowired
  private val customerRepository: CustomerRepository = null

  @ApiOperation(value = "Put_Customers", notes = "method to create new Customer or update customer")
  @ApiResponses(value = Array(
    new ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Bad Request"),
    new ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"),
    new ApiResponse(code = HttpURLConnection.HTTP_ACCEPTED, response = classOf[Customer], message = "Success PUT")
  ))
  @RequestMapping(
    value = Array("/"),
    method = Array(RequestMethod.PUT, RequestMethod.POST, RequestMethod.PATCH),
    produces = Array(MediaType.APPLICATION_JSON_UTF8_VALUE))
  def setCustomer(
                   @Valid @RequestBody customer: Customer
                 ): ResponseEntity[Customer] = {

    val customerExisted = customerRepository.findByEmail(customer.email)
    if (customerExisted != null) {
      customer.id = customerExisted.id
      customer.version = customerExisted.version
    }
    val customerSaved = customerRepository.save(customer)

    new ResponseEntity[Customer](customerSaved, HttpStatus.ACCEPTED)
  }

} 
开发者ID:fpeyron,项目名称:sample-scala-mongo-rest,代码行数:47,代码来源:CustomerController.scala


示例2: request

//设置package包名称以及导入依赖的类
import java.net.{HttpURLConnection, URL}
import scala.util.Try


  def request(method:String, uri: String, data:String, headers: List[Header]):Try[Response] = {

    Try({
      val obj:URL = new java.net.URL(uri)
      val connection:HttpURLConnection = obj.openConnection().asInstanceOf[HttpURLConnection]
      connection.setRequestMethod(method)

      headers.foreach(item => connection.setRequestProperty(item.property, item.value))

      if (data != null && ("POST".equals(method) || "PUT".equals(method))) {
        connection.setDoOutput(true)
        val dataOutputStream = new java.io.DataOutputStream(connection.getOutputStream())

        dataOutputStream.writeBytes(data)
        dataOutputStream.flush()
        dataOutputStream.close()
      }

      val responseCode = connection.getResponseCode
      val responseMessage = connection.getResponseMessage

      if (isOk(responseCode)) {
        val responseText = new java.util.Scanner(connection.getInputStream, "UTF-8").useDelimiter("\\A").next()
        new Response(responseCode, responseMessage, responseText)
      } else {
        new Response(responseCode, responseMessage, null)
      }
    })
  }
} 
开发者ID:bots-squad,项目名称:tentacle-scala,代码行数:35,代码来源:package.scala


示例3: md

//设置package包名称以及导入依赖的类
package mesosphere.marathon
package io

import java.math.BigInteger
import java.net.{ HttpURLConnection, URL, URLConnection }
import java.security.MessageDigest

import mesosphere.marathon.stream._
import org.apache.commons.io.FilenameUtils.getName

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

trait PathFun {

  private[this] def md = MessageDigest.getInstance("SHA-1")

  def mdHex(in: String): String = {
    val ret = md
    ret.update(in.getBytes("UTF-8"), 0, in.length)
    new BigInteger(1, ret.digest()).toString(16)
  }

  def fileName(url: URL): String = getName(url.getFile)

  def contentPath(url: URL): Future[String] = contentHeader(url).map { header =>
    //filter only strong eTags and make sure, it can be used as path
    val eTag: Option[String] = header.get("ETag")
      .flatMap(_.filterNot(_.startsWith("W/")).headOption)
      .map(_.replaceAll("[^A-z0-9\\-]", ""))
    val contentPart = eTag.getOrElse(IO.mdSum(url.openStream()))
    s"$contentPart/${fileName(url)}"
  }

  def contentHeader(url: URL): Future[Map[String, List[String]]] = Future {
    val connection = url.openConnection() match {
      case http: HttpURLConnection =>
        http.setRequestMethod("HEAD")
        http
      case other: URLConnection => other
    }
    scala.concurrent.blocking(connection.getHeaderFields)
      .map { case (key, list) => (key, list.toList) }(collection.breakOut)
  }

} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:47,代码来源:PathFun.scala


示例4: UrlReader

//设置package包名称以及导入依赖的类
// UrlReader.scala
package com.peopledesigned.askrtd.util
import java.util.Base64

object UrlReader {
  @throws(classOf[java.io.IOException])
  @throws(classOf[java.net.SocketTimeoutException])
  def get(url: String,
      connectTimeout: Int = 5000,
      readTimeout: Int = 5000,
      requestMethod: String = "GET") = getWithAuthentication(url, connectTimeout, readTimeout, requestMethod)

  def getAuthenticated(url: String,
      connectTimeout: Int = 5000,
      readTimeout: Int = 5000,
      requestMethod: String = "GET",
      authStr: Option[String] = None) = getWithAuthentication(url, connectTimeout, readTimeout, requestMethod, authStr)

  def getAuthenticatedStream(url: String,
      connectTimeout: Int = 5000,
      readTimeout: Int = 5000,
      requestMethod: String = "GET") = getWithAuthenticationStream(url, connectTimeout, readTimeout, requestMethod, Some("RTDgtfsRT:realT!m3Feed"))

  def getWithAuthentication(url: String,
      connectTimeout: Int = 5000,
      readTimeout: Int = 5000,
      requestMethod: String = "GET",
      authStr: Option[String] = None) =
  {
    val inputStream = getWithAuthenticationStream(url, connectTimeout, readTimeout, requestMethod, authStr)
    val content = io.Source.fromInputStream(inputStream).mkString
    if (inputStream != null) inputStream.close
    content
  }

  def getWithAuthenticationStream(url: String,
      connectTimeout: Int = 5000,
      readTimeout: Int = 5000,
      requestMethod: String = "GET",
      authStr: Option[String] = None) =
  {
    import java.net.{URL, HttpURLConnection}
    val connection = (new URL(url)).openConnection.asInstanceOf[HttpURLConnection]
    if (!authStr.isEmpty) {
      val bytesEncoded = Base64.getEncoder().encodeToString(authStr.get.getBytes());
      connection.setRequestProperty("Authorization", "Basic "+bytesEncoded);
    }
    connection.setConnectTimeout(connectTimeout)
    connection.setReadTimeout(readTimeout)
    connection.setRequestMethod(requestMethod)
    connection.getInputStream
  }
} 
开发者ID:Java1Guy,项目名称:alexa-askrtd-skill,代码行数:54,代码来源:UrlReader.scala


示例5: get

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

trait Connection {
  @throws(classOf[java.io.IOException])
  @throws(classOf[java.net.SocketTimeoutException])
  def get(url: String,
    connectTimeout: Int = 5000,
    readTimeout: Int = 5000,
    requestMethod: String = "GET") =
    {
      import java.net.{URL, HttpURLConnection}
      val connection = (new URL(url)).openConnection.asInstanceOf[HttpURLConnection]
      connection.setConnectTimeout(connectTimeout)
      connection.setReadTimeout(readTimeout)
      connection.setRequestMethod(requestMethod)
      val inputStream = connection.getInputStream
      val content = io.Source.fromInputStream(inputStream).mkString
      if (inputStream != null) inputStream.close
      content
    }
} 
开发者ID:jonatantierno,项目名称:rhymes,代码行数:22,代码来源:Connection.scala


示例6: CheckConnection

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

import java.net.{ConnectException, HttpURLConnection, SocketException, URL}

import org.slf4j.Logger
import org.slf4j.LoggerFactory


object CheckConnection {
  val logger: Logger = LoggerFactory.getLogger(CheckConnection.getClass)

  def checkConnection(): Boolean = {
    var available: Boolean = false
    val urlString: String = "http://localhost:9092"

    try {
      val url: URL = new URL(urlString)
      val con: HttpURLConnection = url.openConnection.asInstanceOf[HttpURLConnection]
      con.setRequestMethod("GET")
      val responseCode: Int = con.getResponseCode
      logger.debug("responseCode={}", responseCode)
    }
    catch {
      case e: ConnectException => logger.error("No connection with Kafka server. Error: {}", e.getMessage)
      case e: SocketException =>
        logger.info("Kafka server is available. {}", e.getMessage)
        available = true
      case e: Exception => logger.error("Failure", e)
    }
    available
  }

  def main(args: Array[String]): Unit = {
    logger.debug("==>CheckConnection")
    logger.debug("Is Kafka server available: {}", checkConnection())
    logger.debug("<==CheckConnection")
  }
} 
开发者ID:ysden123,项目名称:poc,代码行数:39,代码来源:CheckConnection.scala


示例7: ImageService

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

import scala.xml._

class ImageService {
  def findWithTag(tags: String): List[Image] = {
    val xml = XML.loadString(retrieveImageXML(tags))
    val images = (xml \ "entry" \ "link")
      .filter((image: Node) => {
        image.attribute("type").get.toString == "image/jpeg"
      })
      .map((image: Node) => {
        Image(image.attribute("href").get.toString())
    })
    .toList

    images
  }

  private def retrieveImageXML(query: String): String = {
    import java.net.{URL, HttpURLConnection}
    val connection = new URL(s"https://api.flickr.com/services/feeds/photos_public.gne?tags=$query").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 Image(url: String) 
开发者ID:kajstrom,项目名称:EFP-Scala,代码行数:38,代码来源:ImageService.scala


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


示例9: amiId

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

import java.io.{BufferedReader, InputStreamReader}
import java.net.{HttpURLConnection, URL}

import scala.collection.JavaConverters._

trait Accessor {
  private val base = "http://169.254.169.254/latest/meta-data/"
  def amiId: String = doRequest("ami-id")
  def hostName: String = doRequest("hostname")
  def instanceId: String = doRequest("instance-id")
  def instanceType: String = doRequest("instance-type")
  def localHostName: String = doRequest("local-hostname")
  def localIpv4: String = doRequest("local-ipv4")
  def publicHostName: String = doRequest("public-hostname")
  def publicIpv4: String = doRequest("public-ipv4")
  private def doRequest(url: URL): String = {
    val conn = url.openConnection().asInstanceOf[HttpURLConnection]
    conn.setRequestMethod("GET")
    conn.connect()
    new BufferedReader(new InputStreamReader(conn.getInputStream))
      .lines()
      .iterator()
      .asScala
      .mkString("\n")
  }
  private def doRequest(url: String): String = doRequest(new URL(base + url))
}
object Accessor extends Accessor 
开发者ID:yuiwai,项目名称:ec2-metadata,代码行数:31,代码来源:Accessor.scala


示例10: Ui

//设置package包名称以及导入依赖的类
import java.net.HttpURLConnection

import sbt.Keys._
import sbt._

import scala.annotation.switch


object Ui {

  lazy val uiVersion: SettingKey[String] = settingKey[String]("Ui version")
  lazy val uiUrl: SettingKey[String => String] = settingKey[String => String]("Construct url for ui downloading")
  lazy val uiCheckoutDir: SettingKey[String] = settingKey[String]("Directory for downloading ui")
  lazy val ui: TaskKey[File] = taskKey[File]("Download ui or return cached")

  lazy val settings = Seq(
    uiUrl := { (s: String) => s"https://github.com/Hydrospheredata/mist-ui/releases/download/v$s/mist-ui-$s.tar.gz" },
    uiVersion := "1.1.3",
    uiCheckoutDir := "ui_local",
    ui := {
      val local = baseDirectory.value / uiCheckoutDir.value
      if (!local.exists()) IO.createDirectory(local)

      val v = uiVersion.value
      val target = local / s"ui-$v"
      if (!target.exists()) {
        val link = url(uiUrl.value(v))
        val targetF = local/ s"ui-$v.tar.gz"
        download(link, targetF)
        Tar.extractTarGz(targetF, target)
      }
      target / "dist"
    }
  )

  def download(url: URL, to: File): Unit = {
    val conn = url.openConnection().asInstanceOf[HttpURLConnection]
    conn.connect()
    (conn.getResponseCode: @switch) match {
      case 301 | 302 =>
        val redirect  = conn.getHeaderField("Location")
        download(sbt.url(redirect), to)
      case 200 =>
        IO.download(url, to)
      case x => throw new RuntimeException(s"Resource at $url response code is $x")
    }
  }
} 
开发者ID:Hydrospheredata,项目名称:mist,代码行数:49,代码来源:Ui.scala


示例11: DevModeBuild

//设置package包名称以及导入依赖的类
import java.net.HttpURLConnection
import java.io.{BufferedReader, InputStreamReader}

import sbt.{IO, File}

object DevModeBuild {

  val ConnectTimeout = 10000
  val ReadTimeout = 10000

  def waitForRequestToContain(uri: String, toContain: String): Unit = {
    waitFor[String](
      makeRequest(uri),
      _.contains(toContain),
      actual => s"'$actual' did not contain '$toContain'"
    )
  }

  def makeRequest(uri: String): String = {
    var conn: java.net.HttpURLConnection = null
    try {
      val url = new java.net.URL(uri)
      conn = url.openConnection().asInstanceOf[HttpURLConnection]
      conn.setConnectTimeout(ConnectTimeout)
      conn.setReadTimeout(ReadTimeout)
      conn.getResponseCode // we make this call just to block until a response is returned.
      val br = new BufferedReader(new InputStreamReader((conn.getInputStream())))
      Stream.continually(br.readLine()).takeWhile(_ != null).mkString("\n").trim()
    }
    finally if(conn != null) conn.disconnect()
  }

  def waitForReloads(file: File, count: Int): Unit = {
    waitFor[Int](
      IO.readLines(file).count(_.nonEmpty),
      _ == count,
      actual => s"Expected $count reloads, but only got $actual"
    )
  }

  def waitFor[T](check: => T, assertion: T => Boolean, error: T => String): Unit = {
    var checks = 0
    var actual = check
    while (!assertion(actual) && checks < 10) {
      Thread.sleep(1000)
      actual = check
      checks += 1
    }
    if (!assertion(actual)) {
      throw new RuntimeException(error(actual))
    }
  }

} 
开发者ID:lagom,项目名称:lagom,代码行数:55,代码来源:Build.scala


示例12: DevModeBuild

//设置package包名称以及导入依赖的类
import sbt._

import scala.annotation.tailrec
import java.net.HttpURLConnection
import java.io.{BufferedReader, InputStreamReader}

object DevModeBuild {

  val ConnectTimeout = 10000
  val ReadTimeout = 10000

  def callFoo(): String = makeRequest("http://localhost:8000/services/%2Ffooservice") { conn =>
    val br = new BufferedReader(new InputStreamReader((conn.getInputStream())))
    val fooAddress = Stream.continually(br.readLine()).takeWhile(_ != null).mkString("\n").trim()
    makeRequest(fooAddress+"/foo") { conn =>
      val br = new BufferedReader(new InputStreamReader((conn.getInputStream())))
      Stream.continually(br.readLine()).takeWhile(_ != null).mkString("\n").trim()
    }
  }

  private def makeRequest[T](uri: String)(body: HttpURLConnection => T): T = {
    var conn: java.net.HttpURLConnection = null
    try {
      val url = new java.net.URL(uri)
      conn = url.openConnection().asInstanceOf[HttpURLConnection]
      conn.setConnectTimeout(ConnectTimeout)
      conn.setReadTimeout(ReadTimeout)
      conn.getResponseCode // we make this call just to block until a response is returned.
      body(conn)
    }
    finally if(conn != null) conn.disconnect()
  }

} 
开发者ID:lagom,项目名称:lagom,代码行数:35,代码来源:Build.scala


示例13: PushRegistry

//设置package包名称以及导入依赖的类
package org.lyranthe.prometheus.client

import java.io.DataOutputStream
import java.net.{HttpURLConnection, URL}

import org.lyranthe.prometheus.client.registry._

import scala.util.control.NonFatal

class PushRegistry(host: String,
                   port: Int,
                   job: String,
                   additionalLabels: Seq[(String, String)])
    extends DefaultRegistry {
  final private val url = {
    val extra =
      if (additionalLabels.isEmpty) ""
      else
        "/" + additionalLabels
          .flatMap(labels => Vector(labels._1, labels._2))
          .mkString("/")
    new URL("http", host, port, s"/metrics/job/$job$extra")
  }

  def push(): Either[Throwable, Boolean] = {
    val conn = url.openConnection().asInstanceOf[HttpURLConnection]
    try {
      conn.setRequestMethod("PUT")
      conn.setRequestProperty("Content-Type", "text/plain; version=0.0.4")
      conn.setConnectTimeout(10 * 1000) // 10s
      conn.setReadTimeout(10 * 1000)    // 10s
      conn.setDoOutput(true)
      conn.connect()
      val output = new DataOutputStream(conn.getOutputStream)
      output.write(TextFormat.output(collect()))
      output.flush()
      val responseCode = conn.getResponseCode
      output.close()

      Right(responseCode == 202)
    } catch {
      case NonFatal(t) => Left(t)
    } finally {
      conn.disconnect()
    }
  }
}

object PushRegistry {
  def apply(host: String, port: Int = 9091)(
      job: String,
      instance: Option[String],
      additionalLabels: (String, String)*): PushRegistry =
    new PushRegistry(host,
                     port,
                     job,
                     instance.map("instance" -> _).toSeq ++ additionalLabels)
} 
开发者ID:fiadliel,项目名称:prometheus_client_scala,代码行数:59,代码来源:PushRegistry.scala


示例14: HarvestUrbanDic

//设置package包名称以及导入依赖的类
import java.net.{URL,HttpURLConnection}

object HarvestUrbanDic {
  val link = """<a (class="popular" )?href="/define.php\?term=[^"]*">([^<]*)</a>""".r

  def main(args : Array[String]) {
    val out = new java.io.PrintWriter("terms.txt")

    for(letter <- "ABCDEFGHIJKLMNOPQRSTUVWXYZ") {
      var page = 1
      var found = true
      while(found) {
        found = false
        val req = new URL(
          "http://www.urbandictionary.com/browse.php?character=%s&page=%d" 
                format (letter, page))
                  .openConnection()
                  .asInstanceOf[HttpURLConnection]
        if(req.getResponseCode() == 200) {
            for(line <- io.Source.fromInputStream(req.getInputStream()).getLines) {
              link.findAllMatchIn(line).foreach({
                m =>
                  val term = m.group(2)
                  val pop = m.group(1)
                  println(term)
                  found = true
                  if(pop != "") {
                    out.println("* " + term)
                  } else {
                    out.println(term)
                  }
              })
            }
        } else {
          found = false
        }
        println("Page: %s %d" format (letter, page))
        java.util.concurrent.TimeUnit.SECONDS.sleep(1)
        page += 1
      }
    }
    out.close
  }
} 
开发者ID:jmccrae,项目名称:cwn-editor,代码行数:45,代码来源:HarvestUrbanDic.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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