LoginSignup
11
9

More than 5 years have passed since last update.

HTTPoisonでプロキシを使用する

Last updated at Posted at 2016-02-17

HTTPoisonライブラリでプロキシを通して使用する方法を調べたのでまとめます。

なお、HTTPoisonを試してみるにあたり、こちらの記事を参考にさせていただきました。
naoya@githubさんの記事を試すには
ElixirのHTTPoisonライブラリの使い方

事前準備

事前準備としてプロジェクトの作成~mix.exsの編集、依存モジュールの取得を行います。

> mix new httpoison_sample
* creating README.md
* creating .gitignore
* creating mix.exs
* creating config
* creating config/config.exs
* creating lib
* creating lib/httpoison_sample.ex
* creating test
* creating test/test_helper.exs
* creating test/httpoison_sample_test.exs

Your Mix project was created successfully.
You can use "mix" to compile it, test it, and more:

    cd httpoison_sample
    mix test

Run "mix help" for more commands.

mix.exsは次の通りです。

def application do
  [applications: [:logger, :httpoison]]                                                                                                end

def deps do
  [{:httpoison, "~> 0.8"},
   {:poison, "~> 1.5"}
  ]
end

依存モジュールを取得して準備完了です。

> mix deps.get
[33mA new Hex version is available (0.10.4), please update with `mix local.hex`
[0m
Running dependency resolution
Dependency resolution completed
  certifi: 0.3.0
  hackney: 1.4.8
  httpoison: 0.8.1
  idna: 1.0.3
  mimerl: 1.0.2
  poison: 1.5.2
  ssl_verify_hostname: 1.0.5
* Getting httpoison (Hex package)
...

Using locally cached package

実装

lib/httpoison_sample.ex を次の通り編集します。

defmodule HttpoisonSample do
    def get_sample do
        url="http://api.openweathermap.org/data/2.5/weather?q=Tokyo.jp&appid=44db6a862fba0b067b1930da0d769e98"

        HTTPoison.start
        res = HTTPoison.get!(url ,[], [{:proxy,"http://proxyserver:8090"}])

        %{"weather" => weather} = Poison.decode!(res.body)
        %{"main" => main} = Enum.at(weather, 0)

        IO.puts main
    end
end

HttpoisonSample.get_sample

実行結果

>mix run
Clouds
Compiled lib/httpoison_sample.ex

補足

ポイントはHTTPoison.get!/3メソッドの
引数optionsにてプロキシサーバーやポート番号、プロキシ認証のユーザID/パスワードを指定することです。
ここは、キーワードリストで指定します。書式は、次の通り。
[{:proxy, "http://プロキシサーバー:ポート番号"},{:proxy_auth, {ユーザーID,パスワード}}]

11
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
9