7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2015-01-04

概要

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\"}]"

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?