1

我在 elixir 中调用 HTTP Rest API

url = "http://localhost:8080/getScoreData"
   case HTTPoison.get(url) do
     {:ok, %{status_code: 200, body: body}} ->
       Logger.info("body is #{inspect(body)}")
       overall_score = Jason.decode!(body, as: [%OverallScore{}])
       {:ok, overall_score}
   end

在网络浏览器中返回

{
      "avgPass": 85.55,
      "avgFail": 14.45,
      "totalStudents": 80.0,
      "myScoreSchema": [
        {
          "average": 80.0,
          "count": 8.0,
          "percent": 80.0,
          "name": "John"
        },
        {
          "average": 0.0,
          "count": 0.0,
          "percent": 0.0,
          "name": "Cena"
        },
        {
          "average": 0.0,
          "count": 0.0,
          "percent": 0.0,
          "name": "Sunny"
        },
        {
          "average": 0.0,
          "count": 0.0,
          "percent": 0.0,
          "name": "Michael"
        }
      ]
    }

但是Logger.info("body is #{inspect(body)}")从上面的代码行开始的日志删除 了数据并返回下面的数据

{
      "avgPass": 85.55,
      "avgFail": 14.45,
      "totalStudents": 80.0,
      "myScoreSchema": [
        {
          "average": 80.0,
          "count": 8.0,
          "percent": 80.0,
          "name": "John"
        },
        {
          "average": 0.0,
          "count": 0.0,
          "percent": 0.0,
          "name": "Cena Sunny Michael"
        }
      ]
    }

尽管这是一个智能功能,但我不想要这个重复数据删除功能。如何避免重复数据删除。

4

1 回答 1

1

要消除 HTTPoison 是否真的进行重复数据删除,您可以先使用 elixir 获取原始响应:

defmodule Testmodule.HttpClient do
  def send_request(request, callback_host, callback_port) when is_integer(callback_port) do

    # Convert to charlist, as that's what the erlang function is expecting.
    some_host_in_net = callback_host |> String.to_charlist

    {:ok, socket} =
      :gen_tcp.connect(some_host_in_net, callback_port, [:binary, packet: :raw, active: false])

    :ok = :gen_tcp.send(socket, request)

    # Check response status
    case :gen_tcp.recv(socket, 0) do
      {:ok, response} -> :ok = :gen_tcp.close(socket)
        response
      {:error, :closed} -> IO.puts "Something went wrong."
    end

  end
end

定义您的测试请求:

def request_pool do
    """
    GET /getScoreData HTTP/1.1
    Host: localhost
    User-Agent: ExampleBrowser/1.0
    Accept: */*

    messagebody here
    """
  end

最后,您可以使用 Elixir/Erlang 来调用您的端点:

Testmodule.HttpClient.send_request(request, "127.0.0.1", 8080)

应该可以让您在浏览器中看到您所看到的内容,此时您可以根据自己的意愿对其进行解析。

但是,一旦您尝试使用 Poison.decode 对其进行转换,请记住它可能会删除您的数据,因为它可能会将重复的键视为对值的更新,而不是允许重复的键存在于映射中。

于 2020-04-14T21:42:44.803 回答