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

在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

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: Age of Ai 设计师:meimeiellie 返回首页