scala调用接口模板
时间: 2023-09-25 07:12:14 浏览: 135
以下是一个Scala调用接口的模板:
```scala
import java.net.{HttpURLConnection, URL}
import java.io._
object ApiCaller {
def callApi(apiUrl: String, requestMethod: String, requestHeaders: Map[String, String], requestBody: String): String = {
val url = new URL(apiUrl)
val connection = url.openConnection().asInstanceOf[HttpURLConnection]
connection.setRequestMethod(requestMethod)
// 设置请求头
requestHeaders.foreach(h => connection.setRequestProperty(h._1, h._2))
// 设置请求体
connection.setDoOutput(true)
val outputStream = connection.getOutputStream
val writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"))
writer.write(requestBody)
writer.flush()
writer.close()
outputStream.close()
// 发送请求
val responseCode = connection.getResponseCode
if (responseCode == HttpURLConnection.HTTP_OK) { // 请求成功
val inputStream = connection.getInputStream
val reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"))
val response = Stream.continually(reader.readLine()).takeWhile(_ != null).mkString("\n")
reader.close()
inputStream.close()
response
} else { // 请求失败
""
}
}
}
```
使用方法:
```scala
val apiUrl = "http://example.com/api"
val requestMethod = "POST"
val requestHeaders = Map("Content-Type" -> "application/json")
val requestBody = "{\"name\":\"John\", \"age\":30}"
val response = ApiCaller.callApi(apiUrl, requestMethod, requestHeaders, requestBody)
```
阅读全文