Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

HTTP Client for vim

// HTTP Client for vim

   1  
   2  " require vimproc( http://tokyo.cool.ne.jp/hopper2/ )"
   3  let g:HTTP = {}
   4  
   5  function g:HTTP.new(host, ...)
   6    let self.host = a:host
   7    if a:0 >= 1
   8      let self.port = a:1
   9    else
  10      let self.port = 80
  11    endif
  12    let self.headers = {'Host': self.host}
  13    let self.query = {}
  14    return deepcopy(self)
  15  endfunction
  16  
  17  function g:HTTP.get(path)
  18    return self.access(a:path, 'GET')
  19  endfunction
  20  
  21  function g:HTTP.head(path)
  22    return self.access(a:path, 'HEAD')
  23  endfunction
  24  
  25  function g:HTTP.access(path, method)
  26    call g:vimproc.load()
  27    let sock = g:vimproc.socket_open(self.host, self.port)
  28    call sock.write(self.make_header(a:path, a:method))
  29    let re = ""
  30    while !sock.eof
  31      let re .= sock.read()
  32    endwhile
  33    call g:vimproc.unload()
  34    return g:HTTP.Response.new(re)
  35  endfunction
  36  
  37  function g:HTTP.make_header(path, method)
  38    let hds = []
  39    call add(hds, a:method . " " . a:path . " HTTP/1.0")
  40  
  41    for key in keys(self.headers)
  42      call add(hds, key . ": " . self.headers[key])
  43    endfor
  44  
  45    return join(hds, "\r\n") . "\r\n\r\n"
  46  endfunction
  47  
  48  let g:HTTP.Response = {}
  49  function g:HTTP.Response.new(str)
  50    call self.parse(a:str)
  51    return deepcopy(self)
  52  endfunction
  53  
  54  function g:HTTP.Response.parse(str)
  55    let lists = split(a:str, "\r\n\r\n")
  56    let header_lists = split(lists[0], "\r\n")
  57    let first = remove(header_lists, 0)
  58    let self.code = matchstr(first, '[1-5]\d\d')
  59    let self.headers = {}
  60    for header in header_lists
  61      let h = split(header, ': ')
  62      let self.headers[h[0]] = join(h[1:], ': ')
  63    endfor
  64    let self.body = join(lists[1:], "\r\n\r\n")
  65  endfunction


   1  
   2  let h = HTTP.new('www.bigbold.com')
   3  let res = h.get('/snippets/')
   4  echo res.headers
   5  if res.code < 400
   6    echo res.body
   7  else
   8    echo 'error ' . res.code
   9  endif

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS