LoginSignup
2
2

More than 5 years have passed since last update.

HTTPieのsessionはSet-Cookieヘッダにも反応してくれる

Last updated at Posted at 2016-12-27

環境

  • HTTPie 0.9.3

地味に便利で重宝しているので書く。

HTTPieは--session={sessionName or path}を付けると、その時のCookieやヘッダ情報をファイルに保持してくれて次回以降のリクエストに利用してくれる。
マニュアルには載っていないのだが、レスポンスのSet-Cookieヘッダにも反応して、それをファイルに保持してくれる。

クライアントサイドセッション内に最終アクセス日時を保持していたりして、リクエストの度に返ってくるCookieが違う場合などは特に便利。

毎リクエスト変化するSet-Cookieを返すサーバが起動していて(サーバのコードは後述)、初めて--sessionのリクエストを実行してみる。

$ http -v --session=test localhost:8080
GET / HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Host: localhost:8080
User-Agent: HTTPie/0.9.3



HTTP/1.1 200 OK
Date: Tue, 27 Dec 2016 09:27:10 GMT
Set-cookie: eiryu_cookie=1482831607601
Transfer-encoding: chunked

上記のようなリクエスト、レスポンスになった場合にHTTPieのセッション情報ファイルは、

$ cat ~/.httpie/sessions/localhost_8080/test.json
{
    "__meta__": {
        "about": "HTTPie session file",
        "help": "https://github.com/jkbrzt/httpie#sessions",
        "httpie": "0.9.3"
    },
    "auth": {
        "password": null,
        "type": null,
        "username": null
    },
    "cookies": {
        "eiryu_cookie": {
            "expires": null,
            "path": "/",
            "secure": false,
            "value": "1482831607601"
        }
    },
    "headers": {}
}

となっており、Set-Cookieの内容がファイルに保持されていることが分かる。
今のセッション情報ファイルをバックアップして、もう1度リクエストを送りdiffを取ってみる。

$ cp -p ~/.httpie/sessions/localhost_8080/test.json ~/.httpie/sessions/localhost_8080/test.json.bk
$ http -v --session=test localhost:8080
GET / HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Cookie: eiryu_cookie=1482831607601
Host: localhost:8080
User-Agent: HTTPie/0.9.3



HTTP/1.1 200 OK
Date: Tue, 27 Dec 2016 09:40:38 GMT
Set-cookie: eiryu_cookie=1482831638983
Transfer-encoding: chunked

リクエストで先ほどのCookieがセットされていることと、レスポンスで別のSet-Cookieヘッダが返ってきていることが分かる。

$ diff -u ~/.httpie/sessions/localhost_8080/test.json.bk ~/.httpie/sessions/localhost_8080/test.json
--- /Users/eiryu/.httpie/sessions/localhost_8080/test.json.bk   2016-12-27 18:40:07.000000000 +0900
+++ /Users/eiryu/.httpie/sessions/localhost_8080/test.json  2016-12-27 18:40:38.000000000 +0900
@@ -14,7 +14,7 @@
             "expires": null,
             "path": "/",
             "secure": false,
-            "value": "1482831607601"
+            "value": "1482831638983"
         }
     },
     "headers": {}

見ての通り、Cookieの値が更新されていることが分かる。

Set-Cookieを返すサーバのコード(Groovy

import java.io.IOException
import java.net.InetSocketAddress

import com.sun.net.httpserver.HttpExchange
import com.sun.net.httpserver.HttpHandler
import com.sun.net.httpserver.HttpServer

class SimpleHttpHandler implements HttpHandler {
    @Override
    public void handle(HttpExchange exchange) throws IOException {
        try {
            def builder = new StringBuilder()

            def bytes = builder.toString().getBytes("UTF-8")
            exchange.getResponseHeaders().add('Set-Cookie' , 'eiryu_cookie=' + new Date().getTime())
            exchange.sendResponseHeaders(200, bytes.length)
            exchange.responseBody.withStream { it.write(bytes) }
        } catch (e) {
            e.printStackTrace()

            def message = "Server Error = ${e}"
            def bytes = message.getBytes("UTF-8")
            exchange.sendResponseHeaders(500, bytes.length)
            exchange.responseBody.withStream { it.write(bytes) }
        }
    }
}

server = HttpServer.create(new InetSocketAddress(8080), 0)
server.createContext("/", new SimpleHttpHandler())
server.start()

println("LightHttpd Startup. ${new Date()}")

参考

2
2
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
2
2