Class: Tcat::HttpClient

Inherits:
Object
  • Object
show all
Defined in:
lib/tcat/http_client.rb

Defined Under Namespace

Classes: RequestError

Constant Summary collapse

DEFAULT_HEADERS =
{
  'User-Agent' => 'BlackCat/3 (iPhone; iOS 26.2; Scale/3.00)',
  'Accept-Language' => 'en-TW;q=1, zh-Hant-TW;q=0.9',
  'Accept' => '*/*',
  'Accept-Encoding' => 'gzip, deflate, br',
  'Connection' => 'keep-alive'
}.freeze
API_ENDPOINT =
'https://www.t-cat.com.tw/iPhone/TCatApp.aspx'
API_VERSION =
'25'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(timeout: 30) ⇒ HttpClient

Returns a new instance of HttpClient.



23
24
25
26
# File 'lib/tcat/http_client.rb', line 23

def initialize(timeout: 30)
  @timeout = timeout
  @cookies = {}
end

Instance Attribute Details

#cookiesObject (readonly)

Returns the value of attribute cookies.



21
22
23
# File 'lib/tcat/http_client.rb', line 21

def cookies
  @cookies
end

Instance Method Details

#initialize_session(secret) ⇒ Object



49
50
51
52
53
54
55
56
# File 'lib/tcat/http_client.rb', line 49

def initialize_session(secret)
  params = {
    f: 18,
    secret: secret,
    SVC: 'TCATAPP'
  }
  post(params)
end

#post(params) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/tcat/http_client.rb', line 28

def post(params)
  uri = URI("#{API_ENDPOINT}?ver=#{API_VERSION}")
  http = setup_http_client(uri)

  request = Net::HTTP::Post.new(uri)
  DEFAULT_HEADERS.each { |key, value| request[key] = value }
  request['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'
  request['Cookie'] = build_cookie_header if @cookies.any?
  request.body = URI.encode_www_form(params)

  response = http.request(request)
  extract_cookies(response)
  handle_response(response)
rescue Net::ReadTimeout, Net::OpenTimeout => e
  raise RequestError, "Request timeout: #{e.message}"
rescue SocketError, Net::HTTPError => e
  raise RequestError, "Network error: #{e.message}"
rescue StandardError => e
  raise RequestError, "Unexpected error: #{e.message}"
end