【问题标题】:Using scala spark how to print just the response body value returned from a HTTP post call使用scala spark如何仅打印从HTTP post调用返回的响应正文值
【发布时间】:2020-05-12 21:43:58
【问题描述】:

我有一个烧瓶应用程序,如果我对它执行 cURL,它会返回以下内容:

响应采用 JSON 格式,如下所示:

{"your_field": "hello there buddy"}

我只想获取值“hello there buddy”并打印出来。知道怎么做吗?

我有以下代码:

def myExampleFunction  = ( text: String ) => {

  val result = Http("http://localhost:5001/other/post").postData("{\"my_field\":\"" + text + "\"}")
    .header("Content-Type", "application/json")
    .header("Charset", "UTF-8")
    .option(HttpOptions.readTimeout(10000)).asString

  println("result.body is!! : " + result.body)
  result.body

运行它会打印以下内容:

result.body is!! : {"your_field": "hello there buddy"}

我想要实现的是:

result.body is!! : hello there buddy

【问题讨论】:

  • 我没有设置环境,但是,结果。 your_field 会工作
  • 编译错误:值 your_field 不是 scalaj.http.HttpResponse[String] 的成员

标签: scala apache-spark http-post-vars


【解决方案1】:

result.body的类型为string,将字符串数据解析为json数据提取所需字段。

在下面的代码中,我使用了json4s 库来解析对 json 数据的字符串响应。

  def myExampleFunction  = ( text: String ) => {
    import org.json4s._
    import org.json4s.native.JsonMethods._
    implicit val formats = DefaultFormats

    val result = Http("http://localhost:5001/other/post")
      .postData("{\"my_field\":\"" + text + "\"}")
      .header("Content-Type", "application/json")
      .header("Charset", "UTF-8")
      .option(HttpOptions.readTimeout(10000))
      .asString

    (parse(result.body) \\ "your_field").extract[String]
}

【讨论】:

  • 如果我使用 parse(result.body \\ "your_field" 并传递给一个变量并打印它。然后它只打印JString() - 而不是hello there buddy - 知道为什么吗?跨度>
  • 我已经更新了答案 .. 你已经调用 .extract[String] 来提取字符串值。让我知道它是否不起作用
猜你喜欢
  • 2016-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-18
  • 2014-09-11
  • 2020-11-10
相关资源
最近更新 更多