Snusmumriken

Lua webget

Mar 23rd, 2017
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. local function get(path, data)
  2. local host, path = path:match('(.-)(/.*)')
  3. local req = [[
  4. GET %s HTTP/1.1
  5. Host: %s
  6. User-Agent: Unknown agent
  7. Accept: plain/text
  8. Connection: close
  9.  
  10. ]]
  11. local http, err = require'socket'.connect(host, 80)
  12. if not http then return nil, err end
  13. http:settimeout(5)
  14.  
  15. if data then
  16. local post = {}
  17. for key, value in pairs(data) do table.insert(post, ('%s=%s'):format(key,value)) end
  18. path = '?'..table.concat(post, '&')
  19. end
  20.  
  21. http:send(req:format(path, host))
  22. local headers, response = {}, ''
  23.  
  24. local data = http:receive('*a')
  25. print(data)
  26. local splitter = data:find('\r\n\r\n')
  27. local head = data:sub(1, splitter+2)
  28. response = data:sub(splitter+4)
  29. for line in head:gmatch('(.-)\n') do
  30. key, value = line:match('(.-):(.*)')
  31. headers[key] = value
  32. end
  33. return response, headers
  34. end
  35.  
  36. local function post(site, data, mime)
  37. local host, path
  38. if site:find('/') then
  39. host, path = site:match('(.*)(/.*)')
  40. else
  41. host, path = site, '/'
  42. end
  43. local req = [[
  44. POST %s HTTP/1.1
  45. Host: %s
  46. User-Agent: Unknown agent
  47. Content-Type: %s
  48. Content-Length: %d
  49. Connection: close
  50.  
  51. %s]]
  52. local http, err = require'socket'.connect(host, 80)
  53. if not http then return nil, err end
  54. http:settimeout(5)
  55.  
  56. local post = {}
  57. for key, value in pairs(data) do table.insert(post, ('%s=%s'):format(key,value)) end
  58. post = table.concat(post, '&')
  59. req = req:format(path, host, (mime or 'application/x-www-form-urlencoded'), #post, post)
  60. http:send(req)
  61. local headers, response = {}, ''
  62. local data = http:receive('*a')
  63. local splitter = data:find('\r\n\r\n')
  64. local head = data:sub(1, splitter+2)
  65. response = data:sub(splitter+4)
  66. for line in head:gmatch('(.-)\n') do
  67. key, value = line:match('^(.-):(.*)$')
  68. if key and value then
  69. headers[key] = value
  70. else
  71. headers.code, headers.status = line:match('(%d%d%d) (.*)$')
  72. headers.code = headers.code and tonumber(headers.code)
  73. end
  74. end
  75. return response, headers
  76. end
Advertisement
Add Comment
Please, Sign In to add comment