SlideShare une entreprise Scribd logo
1  sur  21
Télécharger pour lire hors ligne
Fake my Party
      Tanja Otto

     24.11.2009
  Düsseldorf on Rails
SalesLentz::DevTeam
Über mich
• internes Entwicklerteam von Sales-Lentz
• IBEs für Reisen, Bustickets, Eventtickets
• seit 2006 entwickeln wir mit Ruby on Rails
• Mit Hussein Morsy Buch Ruby on Rails 2
  Galileo Press
  http://www.railsbuch.de
  http://twitter.com/ajnato
  http://devteam.sales-lentz.lu
HTTParty

• einfaches senden von HTTP-Anfragen
• JSON und XML werden automatisch in
  Ruby-Hashes umgewandelt
• http://github.com/jnunemaker/httparty
HTTParty

XML

         HTTParty   HASH

JSON
Installation


sudo gem install httparty
Ein erstes Beispiel
require "rubygems"
require "httparty"

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')

#   puts   response.body
#   puts   response.code # => 200
#   puts   response.message # => OK
#   puts   response.headers.inspect

response.each do |item|
  puts item['user']['screen_name']
end

#   =>   alexmedeiros59
#   =>   EmySayers
#   =>   ciquuuee
#   =>   bray1972
#   =>   shasoGORGEOUS
#   =>   kimix
Beispiel Twitter-API
class Twitter
  include HTTParty
  base_uri 'twitter.com'

  def initialize(u, p)
    @auth = {:username => u, :password => p}
  end

  def timeline(which=:friends, options={})
    options.merge!({:basic_auth => @auth})
    self.class.get("/statuses/#{which}_timeline.json", options)
  end

  def post(text)
    options = { :query => {:status => text}, :basic_auth => @auth }
    self.class.post('/statuses/update.json', options)
  end
end

twitter = Twitter.new(USERNAME, PASSWORD)
pp twitter.timeline.map{|t| t['user']['name']}
weitere Beispiele

• http://github.com/jnunemaker/httparty/tree/
  master/examples
FakeWeb
• Helper, um HTTP-Anfragen zu stubben
• Testumgebungen von live-Anfragen
  entkoppeln
• Tests sind auch lauffähig, wenn keine
  Netzwerkverbindung besteht
• arbeitet mit allen Libraries die auf
  Net::HTTP basieren
• http://github.com/chrisk/fakeweb/
Installation


sudo gem install fakeweb
Mit einfacher
     Zeichenkette antworten
require "rubygems"
require "fakeweb"
require "httparty"

FakeWeb.register_uri(:get, "http://twitter.com/statuses/
public_timeline.json", :body => "Hello World!")

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body
# => Hello World!

response = HTTParty.get('http://search.twitter.com/trends.json')
puts response.body
# es wird die Antwort der echten Anfrage zurückgeliefert
Einer Antwort einen
             Status hinzufügen
require "rubygems"
require "fakeweb"
require "httparty"

FakeWeb.register_uri(:get, "http://twitter.com/statuses/
public_timeline.json",
                     :body => "Nothing found",
                     :status => ["404", "Not Found"])

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.code # => "404"
puts response.message # => "Not Found"
puts response.body # => "Nothing found"
Auf jede HTTP
            Methode antworten
require "rubygems"
require "fakeweb"
require "httparty"

FakeWeb.register_uri(:any, "http://twitter.com/statuses/
public_timeline.json", :body => "response for any HTTP method")

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body
# => response for any HTTP method

response = HTTParty.post('http://twitter.com/statuses/public_timeline.json')
puts response.body
# response for any HTTP method
Wiederholende Anfragen
require "rubygems"
require "fakeweb"
require "httparty"

FakeWeb.register_uri(:get, "http://twitter.com/statuses/public_timeline.json",
                     [{:body => "Public Timeline", :status => ["200", "OK"]},
                      {:body => "Timeline not found", :status => ["404", "Not
Found"]}])

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body # => Public Timeline
puts response.code # => 200
puts response.message # => OK

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body # => Timeline not found
puts response.code # => 404
puts response.message # => Not Found

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body # => Timeline not found
puts response.code # => 404
puts response.message # => Not Found
Wiederholende Anfragen
require "rubygems"
require "fakeweb"
require "httparty"

FakeWeb.register_uri(:get, "http://twitter.com/statuses/
public_timeline.json",
                     [{:body => "Public Timeline", :status => ["200",
"OK"], :times => 2},
                       {:body => "Timeline not found", :status => ["404",
"Not Found"]}])

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body # => Public Timeline

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body # => Public Timeline

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body # => Timeline not found
HTTP Authentifizierung
require "rubygems"
require "fakeweb"
require "httparty"

FakeWeb.register_uri(:get, "http://example.com/secret", :body =>
"Unauthorized", :status => ["401", "Unauthorized"])
FakeWeb.register_uri(:get, "http://user:pwd@example.com/secret", :body =>
"Authorized")

response = HTTParty.get('http://example.com/secret')
puts response.body # => Unauthorized

response = HTTParty.get('http://example.com/secret', :basic_auth => {:username
=> "user", :password => "pwd"})
puts response.body # => Authorized
Alle registrierten URIs
               löschen
require "rubygems"
require "fakeweb"
require "httparty"

FakeWeb.register_uri(:get, "http://twitter.com/statuses/
public_timeline.json", :body => "Hello World!")

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body
# => Hello World!

FakeWeb.clean_registry

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body
# es wird die Antwort der echten Anfrage zurückgeliefert
Alle live Anfragen
                   blockieren
require "rubygems"
require "fakeweb"
require "httparty"

FakeWeb.allow_net_connect = false

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
# => raises FakeWeb::NetConnectNotAllowedError


require "rubygems"
require "fakeweb"
require "httparty"

# default
FakeWeb.allow_net_connect = true

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
# live Anfrage wird gesendet
automatisches einlesen
            einer Datei
<?xml version="1.0" encoding="UTF-8"?>
<countries>
  <country>Belgien</country>
  <country>Deutschland</country>
  <country>Luxembourg</country>
</countries>


require "rubygems"
require "httparty"
require "fakeweb"

FakeWeb.register_uri(:get, "http://example.com/countries.xml", :body =>
'fixtures/countries.xml', :content_type => "text/xml")

response = HTTParty.get('http://example.com/countries.xml')
puts response.inspect
# => {"countries"=>{"country"=>["Belgien", "Deutschland", "Luxembourg"]}}
HTTP response
             headers definieren
require "rubygems"
require "fakeweb"
require "httparty"

FakeWeb.register_uri(:get, "http://twitter.com/statuses/
public_timeline.json",
                     :body => "Hello World!",
                     :content_type => "text/plain")

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body # => Hello World!
puts response.headers.inspect # => {"content-type"=>["text/plain"]}

Contenu connexe

Tendances

The report of JavaOne2011 about groovy
The report of JavaOne2011 about groovyThe report of JavaOne2011 about groovy
The report of JavaOne2011 about groovy
Yasuharu Nakano
 
Apache CouchDB talk at Ontario GNU Linux Fest
Apache CouchDB talk at Ontario GNU Linux FestApache CouchDB talk at Ontario GNU Linux Fest
Apache CouchDB talk at Ontario GNU Linux Fest
Myles Braithwaite
 
JavaScript APIs - The Web is the Platform
JavaScript APIs - The Web is the PlatformJavaScript APIs - The Web is the Platform
JavaScript APIs - The Web is the Platform
Robert Nyman
 

Tendances (20)

A Gentle Introduction to Event Loops
A Gentle Introduction to Event LoopsA Gentle Introduction to Event Loops
A Gentle Introduction to Event Loops
 
REST with Eve and Python
REST with Eve and PythonREST with Eve and Python
REST with Eve and Python
 
The report of JavaOne2011 about groovy
The report of JavaOne2011 about groovyThe report of JavaOne2011 about groovy
The report of JavaOne2011 about groovy
 
Cross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App EngineCross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App Engine
 
async/await in Swift
async/await in Swiftasync/await in Swift
async/await in Swift
 
Fun with Python
Fun with PythonFun with Python
Fun with Python
 
Pydata-Python tools for webscraping
Pydata-Python tools for webscrapingPydata-Python tools for webscraping
Pydata-Python tools for webscraping
 
RESTFUL SERVICES MADE EASY: THE EVE REST API FRAMEWORK - Nicola Iarocci - Co...
RESTFUL SERVICES MADE EASY: THE EVE REST API FRAMEWORK -  Nicola Iarocci - Co...RESTFUL SERVICES MADE EASY: THE EVE REST API FRAMEWORK -  Nicola Iarocci - Co...
RESTFUL SERVICES MADE EASY: THE EVE REST API FRAMEWORK - Nicola Iarocci - Co...
 
Apache CouchDB talk at Ontario GNU Linux Fest
Apache CouchDB talk at Ontario GNU Linux FestApache CouchDB talk at Ontario GNU Linux Fest
Apache CouchDB talk at Ontario GNU Linux Fest
 
Asynchronous PHP and Real-time Messaging
Asynchronous PHP and Real-time MessagingAsynchronous PHP and Real-time Messaging
Asynchronous PHP and Real-time Messaging
 
KCDC 2018 - Rapid API Development with Sails
KCDC 2018 - Rapid API Development with SailsKCDC 2018 - Rapid API Development with Sails
KCDC 2018 - Rapid API Development with Sails
 
Getting testy with Perl
Getting testy with PerlGetting testy with Perl
Getting testy with Perl
 
Keep it simple web development stack
Keep it simple web development stackKeep it simple web development stack
Keep it simple web development stack
 
Web Scraping with Python
Web Scraping with PythonWeb Scraping with Python
Web Scraping with Python
 
JavaScript APIs - The Web is the Platform
JavaScript APIs - The Web is the PlatformJavaScript APIs - The Web is the Platform
JavaScript APIs - The Web is the Platform
 
Python, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDBPython, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDB
 
Desafios do Profissionalismo Ágil
Desafios do Profissionalismo ÁgilDesafios do Profissionalismo Ágil
Desafios do Profissionalismo Ágil
 
Web Crawling Modeling with Scrapy Models #TDC2014
Web Crawling Modeling with Scrapy Models #TDC2014Web Crawling Modeling with Scrapy Models #TDC2014
Web Crawling Modeling with Scrapy Models #TDC2014
 
Logstash for SEO: come monitorare i Log del Web Server in realtime
Logstash for SEO: come monitorare i Log del Web Server in realtimeLogstash for SEO: come monitorare i Log del Web Server in realtime
Logstash for SEO: come monitorare i Log del Web Server in realtime
 
How to Scrap Any Website's content using ScrapyTutorial of How to scrape (cra...
How to Scrap Any Website's content using ScrapyTutorial of How to scrape (cra...How to Scrap Any Website's content using ScrapyTutorial of How to scrape (cra...
How to Scrap Any Website's content using ScrapyTutorial of How to scrape (cra...
 

Similaire à Fake My Party

Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
Michelangelo van Dam
 
Tips and tricks for building api heavy ruby on rails applications
Tips and tricks for building api heavy ruby on rails applicationsTips and tricks for building api heavy ruby on rails applications
Tips and tricks for building api heavy ruby on rails applications
Tim Cull
 

Similaire à Fake My Party (20)

Let's read code: python-requests library
Let's read code: python-requests libraryLet's read code: python-requests library
Let's read code: python-requests library
 
Palestra VCR
Palestra VCRPalestra VCR
Palestra VCR
 
Let's read code: the python-requests library
Let's read code: the python-requests libraryLet's read code: the python-requests library
Let's read code: the python-requests library
 
Api
ApiApi
Api
 
Web Server.pdf
Web Server.pdfWeb Server.pdf
Web Server.pdf
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
 
JSON and the APInauts
JSON and the APInautsJSON and the APInauts
JSON and the APInauts
 
Get Real: Adventures in realtime web apps
Get Real: Adventures in realtime web appsGet Real: Adventures in realtime web apps
Get Real: Adventures in realtime web apps
 
REST meets Semantic Web
REST meets Semantic WebREST meets Semantic Web
REST meets Semantic Web
 
Using and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareUsing and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middleware
 
API Days Paris - Automatic Testing of (RESTful) API Documentation
API Days Paris - Automatic Testing of (RESTful) API DocumentationAPI Days Paris - Automatic Testing of (RESTful) API Documentation
API Days Paris - Automatic Testing of (RESTful) API Documentation
 
YDN KR Tech Talk : Pipes 와 YQL 활용하기
YDN KR Tech Talk : Pipes 와 YQL 활용하기YDN KR Tech Talk : Pipes 와 YQL 활용하기
YDN KR Tech Talk : Pipes 와 YQL 활용하기
 
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHP
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
 
Servlets intro
Servlets introServlets intro
Servlets intro
 
Tips and tricks for building api heavy ruby on rails applications
Tips and tricks for building api heavy ruby on rails applicationsTips and tricks for building api heavy ruby on rails applications
Tips and tricks for building api heavy ruby on rails applications
 
Velocity EU 2014 — Offline-first web apps
Velocity EU 2014 — Offline-first web appsVelocity EU 2014 — Offline-first web apps
Velocity EU 2014 — Offline-first web apps
 
Blog Hacks 2011
Blog Hacks 2011Blog Hacks 2011
Blog Hacks 2011
 
Server Side Swift: Vapor
Server Side Swift: VaporServer Side Swift: Vapor
Server Side Swift: Vapor
 
Spiffy Applications With JavaScript
Spiffy Applications With JavaScriptSpiffy Applications With JavaScript
Spiffy Applications With JavaScript
 

Dernier

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Dernier (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 

Fake My Party

  • 1. Fake my Party Tanja Otto 24.11.2009 Düsseldorf on Rails
  • 3. Über mich • internes Entwicklerteam von Sales-Lentz • IBEs für Reisen, Bustickets, Eventtickets • seit 2006 entwickeln wir mit Ruby on Rails • Mit Hussein Morsy Buch Ruby on Rails 2 Galileo Press http://www.railsbuch.de http://twitter.com/ajnato http://devteam.sales-lentz.lu
  • 4. HTTParty • einfaches senden von HTTP-Anfragen • JSON und XML werden automatisch in Ruby-Hashes umgewandelt • http://github.com/jnunemaker/httparty
  • 5. HTTParty XML HTTParty HASH JSON
  • 7. Ein erstes Beispiel require "rubygems" require "httparty" response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') # puts response.body # puts response.code # => 200 # puts response.message # => OK # puts response.headers.inspect response.each do |item| puts item['user']['screen_name'] end # => alexmedeiros59 # => EmySayers # => ciquuuee # => bray1972 # => shasoGORGEOUS # => kimix
  • 8. Beispiel Twitter-API class Twitter include HTTParty base_uri 'twitter.com' def initialize(u, p) @auth = {:username => u, :password => p} end def timeline(which=:friends, options={}) options.merge!({:basic_auth => @auth}) self.class.get("/statuses/#{which}_timeline.json", options) end def post(text) options = { :query => {:status => text}, :basic_auth => @auth } self.class.post('/statuses/update.json', options) end end twitter = Twitter.new(USERNAME, PASSWORD) pp twitter.timeline.map{|t| t['user']['name']}
  • 10. FakeWeb • Helper, um HTTP-Anfragen zu stubben • Testumgebungen von live-Anfragen entkoppeln • Tests sind auch lauffähig, wenn keine Netzwerkverbindung besteht • arbeitet mit allen Libraries die auf Net::HTTP basieren • http://github.com/chrisk/fakeweb/
  • 12. Mit einfacher Zeichenkette antworten require "rubygems" require "fakeweb" require "httparty" FakeWeb.register_uri(:get, "http://twitter.com/statuses/ public_timeline.json", :body => "Hello World!") response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # => Hello World! response = HTTParty.get('http://search.twitter.com/trends.json') puts response.body # es wird die Antwort der echten Anfrage zurückgeliefert
  • 13. Einer Antwort einen Status hinzufügen require "rubygems" require "fakeweb" require "httparty" FakeWeb.register_uri(:get, "http://twitter.com/statuses/ public_timeline.json", :body => "Nothing found", :status => ["404", "Not Found"]) response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.code # => "404" puts response.message # => "Not Found" puts response.body # => "Nothing found"
  • 14. Auf jede HTTP Methode antworten require "rubygems" require "fakeweb" require "httparty" FakeWeb.register_uri(:any, "http://twitter.com/statuses/ public_timeline.json", :body => "response for any HTTP method") response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # => response for any HTTP method response = HTTParty.post('http://twitter.com/statuses/public_timeline.json') puts response.body # response for any HTTP method
  • 15. Wiederholende Anfragen require "rubygems" require "fakeweb" require "httparty" FakeWeb.register_uri(:get, "http://twitter.com/statuses/public_timeline.json", [{:body => "Public Timeline", :status => ["200", "OK"]}, {:body => "Timeline not found", :status => ["404", "Not Found"]}]) response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # => Public Timeline puts response.code # => 200 puts response.message # => OK response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # => Timeline not found puts response.code # => 404 puts response.message # => Not Found response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # => Timeline not found puts response.code # => 404 puts response.message # => Not Found
  • 16. Wiederholende Anfragen require "rubygems" require "fakeweb" require "httparty" FakeWeb.register_uri(:get, "http://twitter.com/statuses/ public_timeline.json", [{:body => "Public Timeline", :status => ["200", "OK"], :times => 2}, {:body => "Timeline not found", :status => ["404", "Not Found"]}]) response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # => Public Timeline response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # => Public Timeline response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # => Timeline not found
  • 17. HTTP Authentifizierung require "rubygems" require "fakeweb" require "httparty" FakeWeb.register_uri(:get, "http://example.com/secret", :body => "Unauthorized", :status => ["401", "Unauthorized"]) FakeWeb.register_uri(:get, "http://user:pwd@example.com/secret", :body => "Authorized") response = HTTParty.get('http://example.com/secret') puts response.body # => Unauthorized response = HTTParty.get('http://example.com/secret', :basic_auth => {:username => "user", :password => "pwd"}) puts response.body # => Authorized
  • 18. Alle registrierten URIs löschen require "rubygems" require "fakeweb" require "httparty" FakeWeb.register_uri(:get, "http://twitter.com/statuses/ public_timeline.json", :body => "Hello World!") response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # => Hello World! FakeWeb.clean_registry response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # es wird die Antwort der echten Anfrage zurückgeliefert
  • 19. Alle live Anfragen blockieren require "rubygems" require "fakeweb" require "httparty" FakeWeb.allow_net_connect = false response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') # => raises FakeWeb::NetConnectNotAllowedError require "rubygems" require "fakeweb" require "httparty" # default FakeWeb.allow_net_connect = true response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') # live Anfrage wird gesendet
  • 20. automatisches einlesen einer Datei <?xml version="1.0" encoding="UTF-8"?> <countries> <country>Belgien</country> <country>Deutschland</country> <country>Luxembourg</country> </countries> require "rubygems" require "httparty" require "fakeweb" FakeWeb.register_uri(:get, "http://example.com/countries.xml", :body => 'fixtures/countries.xml', :content_type => "text/xml") response = HTTParty.get('http://example.com/countries.xml') puts response.inspect # => {"countries"=>{"country"=>["Belgien", "Deutschland", "Luxembourg"]}}
  • 21. HTTP response headers definieren require "rubygems" require "fakeweb" require "httparty" FakeWeb.register_uri(:get, "http://twitter.com/statuses/ public_timeline.json", :body => "Hello World!", :content_type => "text/plain") response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # => Hello World! puts response.headers.inspect # => {"content-type"=>["text/plain"]}