21
21

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.

rubyで通信系の関数(Net関数)を使うときに気をつけること

Last updated at Posted at 2014-08-12

textからhrefを見つける方法

  • httpとhttpsを含むurlを取得
text.scan(URI.regexp(['http', 'https'])) do
    p URI.parse($&).to_s
end

UserAgentをつける方法

uri = URI.parse(url)
res = Net::HTTP.start(uri.host, uri.port) do |http|
    http.get(uri.path, {'User-Agent' => UrlConcern::USER_AGENT})
end

イレギュラーなURIのパースについて

  • http:/をopenするとTypeErrorが起きる
URI.parse("http:/").open
-> TypeError: no implicit conversion of nil into String
  • http:http://だとInvalidURIErrorが起きる
URI.parse("http:").open
-> URI::InvalidURIError: bad URI(absolute but no path)
URI.parse("http://").open
-> URI::InvalidURIError: bad URI(absolute but no path)
  • 存在しないパスの場合
URI.parse("http://example.com").open
-> SocketError: getaddrinfo: nodename nor servname provided, or not known

httpからhttpsにredirectする際のエラー

RuntimeError: redirection forbidden: http://**** -> https://****

httpsのデータを取得するとき

uri = URI.parse(url)
res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
    http.get(uri.path)
end

uriがparseできるかどうか

if url =~ URI::regexp
    # Correct URL
end
21
21
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
21
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?