restclient为什么加不上heads

Python014

restclient为什么加不上heads,第1张

这是一个用Ruby封装的访问HTTP和REST client的gem,其中HTTP访问动词(get, put, post, delete)的形式,受到Sinatra的架构风格影响。

当前gem的版本支持Ruby 1.9.3或者更新版本,对于早期的Ruby 1.8.7和1.9.2版本不再提供支持。rest-client自身依赖于其他三个gem:

mime-types

netrc

rdoc

基本使用

原生URL

require 'rest_client'

RestClient.get 'http://example.com/resource'

RestClient.get 'http://example.com/resource', {:params =>{:id =>50, 'foo' =>'bar' }}

RestClient.get 'https://user:[email protected]/private/resource', {:accept =>:json}

RestClient.post 'http://example.com/resource', :param1 =>'one', :nested =>{:param2 =>'two'}

RestClient.post 'http://example.com/resource', { 'x' =>1 }.to_json, :content_type =>:json, :accept =>:json

RestClient.delete 'http://example.com/resource'

response = RestClient.get 'http://example.com/resource'

response.code

->200

response.cookies

->{"Foo"=>"BAR", "QUUX"=>"QUUUUX"}

response.headers

->{:content_type=>"text/htmlcharset=utf-8", :cache_control=>"private"...

response.to_str

->\n<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n \"http://www.w3.org/TR/html4/strict.dtd\">\n\n<html ...

RestClient.post( url,

{

:transfer =>{

:path =>'/foo/bar',

:owner =>'that_guy',

:group =>'those_guys'

},

:upload =>{

:file =>File.new(path, 'rb')

}

}

)

多部件(Multipart)

使用RestClient可以完成多部件的发送。

RestClient.post '/data', :myfile =>File.new("/path/to/image.jpg", 'rb')

上面这句代码做了两件事情:

自动检测作为多部件发送的File类型对象的值

自动检测文件的MIME,并在payload中将其设置到每个实体的HEAD中

如果发送的参数里不包括File对象,那么在payload中需要设置multipart:

RestClient.post '/data', {:foo =>'bar', :multipart =>true}

ActiveResource-Style

resource = RestClient::Resource.new 'http://example.com/resource'

resource.get

private_resource = RestClient::Resource.new 'https://example.com/private/resource', 'user', 'pass'

private_resource.put File.read('pic.jpg'), :content_type =>'image/jpg'

关于这部分,更详细的内容可以参见相关文档。

异常(更多参见w3.org)

状态码在200和207之间,RestClient::Response将会返回

状态码是301,302或307的,如果请求类型是GET或HEAD,随后进行重定向

状态码是303的,请求类型将会变成GET,随后进行重定向

对于其他情况,RestClient::Exception将会被抛出异常;针对已知的错误代码,一个特定的异常将会被抛出

RestClient.get 'http://example.com/resource'

->RestClient::ResourceNotFound: RestClient::ResourceNotFound

begin

RestClient.get 'http://example.com/resource'

rescue =>e

e.response

end

->404 Resource Not Found | text/html 282 bytes

处理Result

一个block会传给RestClient方法。这个代码块随后会被Response调用。Response.return!会执行默认的response行为。

# Don't raise exceptions but return the response

RestClient.get('http://example.com/resource'){|response, request, result| response}

->404 Resource Not Found | text/html 282 bytes

# Manage a specific error code

RestClient.get('http://my-rest-service.com/resource'){|response, request, result, &block|

case response.code

when 200

p "It worked !"

response

when 423

raise SomeCustomExceptionIfYouWant

else

response.return!(request, result, &block)

end

}

# Follow redirections for all request types and not only for get and head

# RFC : "If the 301, 302 or 307 status code is received in response to a request other than GET or HEAD,

# the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user,

# since this might change the conditions under which the request was issued."

RestClient.get('http://my-rest-service.com/resource'){|response, request, result, &block|

if [301, 302, 307].include? response.code

response.follow_redirection(request, result, &block)

else

response.return!(request, result, &block)

end

}

非标准URI(Non-normalized URIs)

如果需要标准化URI,诸如此类。需要让国际化的资源标示(International Resource Identifiers, IRIs)正常工作,可以在代码中使用addressable gem:

require 'addressable/uri'

RestClient.get(Addressable::URI.parse("http://www.詹姆斯.com/").normalize.to_str)

更低层次访问(Lower-level access)

对于一些事例,通用的API并没有覆盖到,你可以使用提供了更低层次(lower-level)API的RestClient::Request类型进行访问。

使用ssl的特定参数

覆盖cookies

手动处理response

更多详细信息可以参照RestClient::Request的文档。

Shell

restclient shell命令提供了一个已经加载过RestClient的IRB session:

$ restclient

>>RestClient.get 'http://example.com'

为resource的访问动词 get/post/put/delete 的URL提供参数

$ restclient http://example.com

>>put '/resource', 'data'

为认证resource添加认证用户和密码:

$ restclient https://example.com user pass

>>delete '/private/resource'

为已经命名的session创建~/.restclient:

sinatra:

url: http://localhost:4567

rack:

url: http://localhost:9292

private_site:

url: http://example.com

username: user

password: pass

然后调用:

restclient private_site

临时使用策略,curl书写风格(curl-style):

restclient get http://example.com/resource >ourput_body

restclient put http://example.com/resource <input_body

日志

开启日志:

使用Ruby Logger设置RestClient.log,或者

为了避免修改代码可以设置一个环境变量(本例中可以使用一个名为”stdout”或”stderr”的文件名):

$ RESTCLIENT_LOG=stdout path/to/my/program

生产环境的log如下:

RestClient.get "http://some/resource"

# =>200 OK | text/html 250 bytes

RestClient.put "http://some/resource", "payload"

# =>401 Unauthorized | application/xml 340 bytes

代理(Proxy)

对于所有调用RestClient,包括Resource的,可以使用RestClient.proxy进行设定:

RestClient.proxy = "http://proxy.example.com/"

RestClient.get "http://some/resource"

# =>response from some/resource as proxied through proxy.example.com

通常情况下,代理的URL通过环境变量进行设置,所以可以通过下面这种方式进行设置:

RestClient.proxy = ENV['http_proxy']

查询参数

请求对象知道进行参数查询并自动把它们添加到GET,HEAD和DELETE的URL请求上,根据需要丢掉key和value:

RestClient.get 'http://example.com/resource', :params =>{:foo =>'bar', :baz =>'qux'}

# will GET http://example.com/resource?foo=bar&baz=qux

Cookies

请求和响应对象知道HTTP的cookie,并根据需要设置或取出header:

response = RestClient.get 'http://example.com/action_which_sets_session_id'

response.cookies

# =>{"_application_session_id" =>"1234"}

response2 = RestClient.post(

'http://localhost:3000/',

{:param1 =>"foo"},

{:cookies =>{:session_id =>"1234"}}

)

# ...response body

SSL客户端认证

RestClient::Resource.new

'https://example.com',

:ssl_client_cert =>OpenSSL::X509::Certificate.new(File.read("cert.pem")),

:ssl_client_key =>OpenSSL::PKey::RSA.new(File.read("key.pem"), "passphrase, if any"),

:ssl_ca_file =>"ca_certificate.pem"

:verify_ssl =>OpenSSL::SSL::VERIFY_PEER

).get

钩子(Hook)

RestClient.add_before_execution_proc在每次调用之前会添加一个Proc。如果需要直接访问HTTP请求会很好用。

# Add oauth support using the oauth gem

require 'oauth'

access_token = ...

RestClient.add_before_execution_proc do |req, params|

access_token.sign! req

end

RestClient.get 'http://example.com'

puts "hello 是写在rb文件中的

eg

app/controllers/hello_controller.rb #画面的控制

class HelloController <ActionController

def index

@hello = "hello"

puts @hello # "hello"

end

end

app/views/hello/index.rhtml

<table border="1">

<tr>

<td><%=@hello%></td> #@hello 或者$hello 这种变量才能在页面中使用

</tr>

</table>

地址是:http://localhost:3000/hello/say

一、下载并安装Ruby

Windows下安装Ruby最好选择 RubyInstaller(一键安装包)。

我们这里下载目前较新的rubyinstaller-1.9.3-p0.exe 一键安装包。这个安装包除了包含ruby本身,还有许多有用的扩展(比如gems)和 帮助文档。

双击安装,安装过程出现如下界面。

这里我们选择安装路径为 D:\Ruby。 下面有3个选项分别是:(1) 是否安装tclTk支持。(2) 添加ruby命令路径到系统环境变量PATH。(3)是否将 .rb 和.rbw 文件关联到Ruby。

这里我们全部打勾。点击“Install” 安装完毕。

打开CMD窗口,运行 ruby -v 显示ruby当前版本号。

你也可以输入 ruby -e 'puts "hello world" ',则显示 hello world。

也可以打开记事本写一段代码如: puts "hello world",保存为 test.rb,然后在CMD中 运行 ruby test.rb 则显示结果 hello world。

我想你不甘心就用记事本来写程序吧,这里推荐一款轻巧的代码编辑器SciTE,支持多种语法高亮显示及高亮导出,且免费开源。以前的RubyInstaller 自带SciTE,而新版需要自己下载。官方地址:scintilla.org windows下有绿色版和安装版,安装版下载 点这里。

安装SciTE后,打开它,我们输入代码 puts "hello world" ,点击菜单=>file=>save 保存文件为test.rb。 然后按键盘F5,右侧输出窗口出现结果。

二、下载并安装RubyGems

RubyGems是一个方便而强大的Ruby程序包管理器,类似RedHat的RPM。它将一个Ruby应用程序打包到一个gem里,作为一个安装单元。 特点:能远程安装包,包之间依赖关系的管理,简单可靠的卸载,查询机制,能查询本地和远程服务器的包信息,能保持一个包的不同版本,基于Web的查看接口,能查看你安装的gem的信息。

从官方下载RubyGems,以zip版本为例,解开压缩包,从CMD提示窗口下进入setup.rb所在目录, 运行 ruby setup.rb 即可安装。

较新的Ruby版本已经包含RubyGems了,因此我们不用手动下载安装了。只需在CMD窗口输入指令:gem update --system ,耐心等待一段时间,已有的RubyGems会更新到目前最新的版本。

三、下载并安装Rails

从CMD提示窗口输入指令:gem install rails 开始安装rails。

如不想安装文档文件,可以输入:gem install rails --no-rdoc --no-ri

程序自动下载并安装rails, 耐心等待。

安装完成后,你可以在路径 D:\Ruby\lib\ruby\gems\1.9.1\gems 看到些东西,都是rails的包文件,与ruby安装在同一目录下。

这时在CMD提示窗口输入指令: rails -v 显示rails的版本号。如图:

四、下载并安装DevKit

DevKit 是windows平台下编译和使用本地C/C++扩展包的工具。它就是用来模拟Linux平台下的make, gcc, sh来进行编译。这个方法目前仅支持通过RubyInstaller安装的Ruby。

下载Devkit:http://rubyinstaller.org/downloads

如果上面的地址打不开,就从这里下载:https://github.com/oneclick/rubyinstaller/downloads/

我们这里使用目前较新的版本 DevKit-tdm-32-4.5.2-20111229-1559-sfx.exe

安装步骤:

1) 将下载 DevKit 解压到 D:\DevKit 目录。

2) 打开 CMD 窗口,进入 D:\DevKit 目录,输入ruby dk.rb init 。#生成config.yml,这里会检查将要添加DevKit支持的Ruby列表,只支持通过RubyInstaller安装的Ruby。

3) 输入 ruby dk.rb install #开始安装。

4) 输入 ruby dk.rb review #检查要添加DevKit支持的Ruby列表是否有误,可以略过。

5) 输入 gem install rdiscount --platform=ruby 。#这一步只是验证DevKit是否安装成功,如果能安装rdiscount成功说明安装DevKit成功,也可以不做。

整个过程如图:

五、创建一个Rails项目

打开CMD提示窗口,进入D盘,输入指令:rails new www ,会在D盘创建名称为www 的rails项目结构。

接着进入www目录,输入指令:rails server ,启动rails自带的 webrick 服务器。

打开浏览器输入地址 http://localhost:3000/ 看到欢迎页面,

下来我们让Rails说 "Hello"

Rails是一个MVC框架,Rails接收来自浏览器的请求,对请求进行解读以找到合适的控制器,再调用控制器中合适的方法。然后,控制调用合适的视图,把结果显示给用户。Rails提供了快速创建视图和控制的方法,打开CMD命令窗口。进入到刚才的www项目目录,输入命令:rails generate controller say hello

下面我打开上图中提示的视图文件,路径是 /项目目录/app/views/say/hello.html.erb

修改为如下形式:

复制代码 代码如下:

<h1>Say#hello</h1>

<p>现在时间是:<%=@time%></p>

注意:将视图文件 hello.html.erb 另存为UTF-8编码格式,否则中文会出现乱码。说明一下是UTF-8编码,而不是 UTF-8 +BOM 编码,BOM 是通过文件开头添加几个字符表示文件编码的标准。但是只有微软用了,x-nix 、PHP、Ruby 不认。

接着打开控制器文件,路径是 /项目目录/app/controllers/say_controller.rb

修改为

复制代码 代码如下:

class SayController <ApplicationController

def hello

@time=Time.now

end

end

打开浏览器访问:http://localhost:3000/say/hello。

如果要更改首页,让首页显示Hello。只需2步:

1) 找到 /项目目录/config/route.rb 文件,查找到这行 # root :to =>'welcome#index' 去掉注释并设置为自己的控制器,修改为 :

root :to =>'say#hello'

2) 删除 /项目目录/public/index.html 文件,因为rails优先读取public目录下的静态文件。

再次访问:http://localhost:3000,首页显示Say#Hello,于上图的内容一致。

六 创建一个使用MySQL数据库的Rails项目

1) 打开CMD窗口,进入D盘,输入命令:rails new work --database Mysql,在D盘创建名称为 work 的rails 项目结构。

2) 必须将libmysql.dll库拷贝到 Ruby安装目录的Bin目录下(D:\Ruby\Bin)。否则在启动服务器时候会提示:“没有找到LIBMYSQL.dll,因此这个应用程序未能启动。重新安装应用程序可能会修复此问题。”

下载地址:http://www.mysql.com/downloads/connector/c/

我们这里下载 mysql-connector-c-noinstall-6.0.2-win32.zip ,解压缩,在lib目录里面的libmysql.dll 就是我们要找的。

3) 修改数据库的配置信息。在 /项目目录/config/database.yml 文件中,分别对应 “开发”、“测试”,“生产” 数据库的配置,把他们修改为自己的配置。

其中development是我们开发中要实际使用的数据库。一定要注意在username: 和 password: 后面至少要保留一个空格。

4) 在CMD窗口输入rake db:craete 命令,会在msyql 中创建由配置信息中所设置的数据库。

5) 我们用scaffold来生成代码,在CMD中输入下面指令:

rails generate scaffold post title:string body:string addTime:datetime

这时候会创建controller, views, models和数据库脚本,但此时还没有创建表。

再输入:rake db:migrate 创建表。完成。

6) 执行命令 rails server