[Scala基础]--调用url获取返回值

本文介绍如何使用Scala的Source类从指定URL获取字符串或文件流形式的数据,并将其写入本地文件。示例展示了如何处理两种类型的返回值:字符串和文件流。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Scala编程中,常常会用到调用第三方接口,获取返回值(文件内容是字符类型,或者返回的是字符串),那么使用Scala自带的Scala.io.Source类,将非常方便。

举例如下:

  1、url="http://localhost:9008/services/user/getSampleValue"

  2、返回值:有两种

       (1)字符串:"{"status":"1","timestamp":"201612131742","sampleList":[{"domain":"www.baidu.cn","proportion":"0.8"},{"domain":"www.sina.com","proportion":"0.4"}]}"

       (2)文件流(内容是字符):sample.txt文件

            内容是:"{"status":"1","timestamp":"201612131742","sampleList":[{"domain":"www.baidu.cn","proportion":"0.8"},{"domain":"www.sina.com","proportion":"0.4"}]}"

实现的代码如下:

import java.io.PrintWriter
import scala.io.Source

/**
  * Created by yangjf on 2016/12/14
  * Update date:
  * Time: 9:35
  * Describle :测试使用Scala调用url
  * Result of Test:通过
  * Command:
  */
object TestScalaUrl {
  def main(args: Array[String]) {
    //获取抽样参数的url
    val url="http://localhost:9008/services/user/getSampleValue"
	//链接url,获取返回值
    val fileContent = Source.fromURL(url,"utf-8").mkString
	//写入本地磁盘
    val pw = new PrintWriter("F:/test.ip")
    pw.write(fileContent)
    pw.flush
    pw.close
  }
  
  //可以从InputStream中读取
    def inputToString(is: java.io.InputStream): String = {
    val lines: Iterator[String] = scala.io.Source.fromInputStream(is, "utf-8").getLines()
    val sb = new StringBuilder()
    lines.foreach(sb.append(_))
    sb.toString()
  }
  
   //将输入流写入文件(test.txt)中
   //参数f---> val file = new File("F:/test.txt")
  def inputToFile(is: java.io.InputStream, f: java.io.File) {
    val in: BufferedSource = scala.io.Source.fromInputStream(is)
    val out = new java.io.PrintWriter(f)
    try {
      in.getLines().foreach(out.print(_))//等价write,只是多了一句if(s==null)s="null"
    }
    finally {
      out.close
    }
  }
  

}


参考Scala 的API:

    http://www.scala-lang.org/api/current/scala/io/Source.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

oo寻梦in记

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值