如何使用Nestful从rails到GET进行POST / GET?

时间:2010-05-09 01:15:35

标签: rest

这是一个非常基本的问题,但我并不完全清楚如何做到这一点。

我正在尝试使用具有基于Web服务的第三方服务。该服务称为Postful。但我不清楚究竟要做什么?

我查看了ActiveResource(http://api.rubyonrails.org/classes/ActiveResource/Base.html)和rest-client,但我仍然不清楚要创建的步骤,代码和文件。

我正在尝试使用Nestful,但我并不完全清楚如何使这项工作。 http://github.com/maccman/nestful

http://www.postful.com/service/mail是其中一项服务(详情见http://www.postful.com/developer/guide#rest),但要上传图片,我必须发布以下内容(但我不确定我是如何做到这一点的?)。谢谢!

> http://www.postful.com/service/upload
> 
> Be sure to include the Content-Type
> and Content-Length headers and the
> image itself as the body of the
> request.
> 
> POST /upload HTTP/1.0 Content-Type:
> application/octet-stream
> Content-Length: 301456
> 
> ... file content here ...
> 
> If the upload is successful, you will
> receive a response like the following:
> 
> <?xml version="1.0" encoding="UTF-8"?>
> <upload>  
> <id>290797321.waltershandy.2</id>
> </upload>

2 个答案:

答案 0 :(得分:1)

我已经查看了他们的API,并且附件上传似乎不是RESTful - 看起来只有邮件订单创建。所以,ActiveResource不会在这里做到这一点。

根据您的开发/制作环境,您可能希望使用更通用的内容,例如curl

从手册中:curl是一种从服务器传输数据或向服务器传输数据的工具......该命令旨在无需用户交互即可工作。

你会想要这样的东西:

# Encode your username:password as base64
USERNAME="youremail@example.com"
PASSWORD="yourpostfulpassword"
BASE64_ENCODED_AUTH = `echo $USERNAME:PASSWORD | base64`

curl -F "@path/to/file/to/upload;type=application/octet-stream" http://$BASE64_ENCODED_AUTH@www.postful.com/service/upload

我没有对此进行测试,因为我没有用户名/密码 - 但它应该让你走上正轨。

您可以将其放在/lib的脚本中,然后使用您首选的方法从控制器中调用它。

修改

所以我尝试使用虚拟用户名和密码,并使用--verbose标记curl,标题看起来正确。我还得到401 UNAUTHORISED响应,因此看起来它正常工作。

答案 1 :(得分:1)

Nestful非常简单,你应该能够做到这一点:

Nestful.post 'http://www.postful.com/service/upload', :format => :multipart, :user => 'foo', :password => 'bar', :params => {:file => File.open('YOUR_FILE')}