创建对tumblr的POST请求

时间:2012-03-21 02:55:54

标签: c# api upload request tumblr

我正在尝试为tumblr api创建一个帖子请求。下面显示的是来自api的摘录:

The Write API is a very simple HTTP interface. To create a post, send a POST request to http://www.tumblr.com/api/write with the following parameters:
    email - Your account's email address.
    password - Your account's password.
    type - The post type.

这些是必不可少的元素。我想发一张照片给api。根据API,这就是我构建请求的方式:

email: myEmail
password: myPassword
type: photo
data: "c:\\img.jpg"

感谢dtb,我可以发送一个REGULAR帖子,它只使用字符串发送文本,但不支持发送图片。

var postData = new NameValueCollection
{
    { "email", email },
    { "password", password },
    { "type", regular },
    { "body", body }
};

using (var client = new WebClient())
{
     client.UploadValues("http://www.tumblr.com/api/write", data: data);
}

这适用于发送常规内容,但根据API,我应该以{{1​​}}发送图片,或者我可以用multipart/form-data发送图片,但是,文件大小不如前者允许的那么高。

Normal POST method支持数据:允许我将client.UploadValues传递给它。
postData也有,但我无法弄清楚如何使用它,我已经参考了文档 此外,打开的文件无法在NameValueCollection中传递,这让我感到困惑,因为我可以发送请求。

如果有人知道答案,请你帮助我,我将非常感激。

2 个答案:

答案 0 :(得分:4)

您可以使用WebClient Class及其UploadValues method来执行application/x-www-form-urlencoded有效负载的POST请求:

var data = new NameValueCollection
{
    { "email", email },
    { "password", password },
    { "type", regular },
    { "body", body }
};

using (var client = new WebClient())
{
     client.UploadValues("http://www.tumblr.com/api/write", data: data);
}

答案 1 :(得分:3)

我能够使用RestSharp库来解决这个问题。

//Create a RestClient with the api's url
var restClient = new RestClient("http://tumblr.com/api/write");

//Tell it to send a POST request
var request = new RestRequest(Method.POST);

//Set format and add parameters and files
request.RequestFormat = DataFormat.Json; //I don't know if this line is necessary

request.AddParameter("email", "EMAIL");
request.AddParameter("password", "PASSWORD");
request.AddParameter("type", "photo");
request.AddFile("data", "C:\\Users\\Kevin\\Desktop\\Wallpapers\\1235698997718.jpg");

//Set RestResponse so you can see if you have an error
RestResponse response = restClient.Execute(request);
//MessageBox.Show(response) Perhaps I could wrap this in a try except?

它有效,但我不确定这是否是最好的方法。

如果有人有更多建议,我很乐意接受他们。