Edited at

EmacsLispでHTTPアクセスするコードを書いてみた

More than 3 years have passed since last update.


概要

EmacsLispでhttpアクセスをする関数を良く探すのでEmacsWikiのUrlPackageを一部改良したものを残します。


コード


POST


定義


  • 引数 url アクセス先のURL

  • 引数 args 送信するPOSTパラメータのリスト

  • 返り値 レスポンスbodyの文字列

(defun url-http-post (url args)

"Send ARGS to URL as a POST request."
(let (
(response-string nil)
(url-request-method "POST")
(url-request-extra-headers
'(("Content-Type" . "application/x-www-form-urlencoded")))
(url-request-data
(mapconcat (lambda (arg)
(concat (url-hexify-string (car arg))
"="
(url-hexify-string (cdr arg))))
args
"&")))
(switch-to-buffer
(url-retrieve-synchronously url))
(goto-char (point-min))
(re-search-forward "\n\n")
(setq response-string
(buffer-substring-no-properties (point) (point-max)))
(kill-buffer (current-buffer))
response-string))


使用例

(url-http-post "http://example.com/post.php"  '(("hoge" . "fuga") ("piyo" . "1"))) ;; => "[{\"hoge\":\"fuga\"},{\"piyo\":\"1\"}]"


GET


定義


  • 引数 url アクセス先のURL

  • 引数 args 送信するGETパラメータのリスト

  • 返り値 レスポンスbodyの文字列

(defun url-http-get (url args)

"Send ARGS to URL as a GET request."
(let (
(response-string nil)
(url-request-method "GET")
(url-request-data
(mapconcat (lambda (arg)
(concat (url-hexify-string (car arg))
"="
(url-hexify-string (cdr arg))))
args
"&")))
(switch-to-buffer
(url-retrieve-synchronously
(concat url "?" url-request-data)))
(goto-char (point-min))
(re-search-forward "\n\n")
(setq response-string
(buffer-substring-no-properties
(point) (point-max)))
(kill-buffer (current-buffer))
response-string))


使用例

(url-http-get "http://example.com/get.php" '(("hoge" . "fuga") ("piyo" . "1")))  ;; => "[{\"hoge\":\"fuga\"},{\"piyo\":\"1\"}]"


参考

http://www.emacswiki.org/UrlPackage