scala调用接口

scala post请求调用http接口返回json数据

package xmadx.statistics

import java.nio.charset.StandardCharsets
import java.util

import com.alibaba.fastjson.{JSON, JSONObject}
import org.apache.commons.httpclient.methods.{PostMethod, StringRequestEntity}
import org.apache.commons.httpclient.{HttpClient}

object ipdate {
  val CONTENT_TEMPLATE = "修改前的余额:%s<br/>修改后的余额:%s"

  def main(args: Array[String]): Unit = {
    val (httpClient, httpPost) = (new HttpClient(), new PostMethod("http://172.81.208.169:8010/log_service/internal/log/add"))
    val req = new JSONObject()
    val (ad, cos) = ("1433.2", "14321.2")

    req.put("context", util.Collections.singletonList(new JSONObject() {
      {
        put("business_sign", "xm_send_order")
        put("module_code", "xmadx_statistics")
        put("content", String.format(CONTENT_TEMPLATE, ad, cos))
        put("service_code", "big_data")
        put("operation_timestamp", System.currentTimeMillis())
        put("operator", "system")
        put("title", "上报小盟派单财务日志")
      }
    }))
    val entity = new StringRequestEntity(req.toJSONString, "application/json", StandardCharsets.UTF_8.name())

    httpPost.setRequestEntity(entity)
    httpClient.executeMethod(httpPost)

    val resp = JSON.parseObject(new String(httpPost.getResponseBody(), StandardCharsets.UTF_8.name()))
    if (resp.get("code") != 0) {
      // todo write error log
    }
  }
}

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页