2012-03-21 181 views
1

我想创建一个tumblr api的发布请求。下面显示的是来自所述api的提取物:创建POST请求到tumblr

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,我可以给一个普通的帖子,只使用一个字符串来发送文本,它不支持发送图像。

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,我应该在multipart/form-data发送图像,
我也可以在Normal POST method发送,
然而,的filesizes不一样高allowd与前者。

client.UploadValues支持数据:它允许我将postData传递给它。
client.UploadData也可以,但我不知道如何使用它,我已经提到了文档。
另外,一个打开的文件不能在NameValueCollection中传递,这让我对如何发送请求感到困惑。

请问,如果有人知道答案,我将非常感激,如果你愿意帮忙。

+1

您显示的C#代码段正在发送GET请求。如果你认为它需要显示更多,实际上,像你的python代码发送POST一样建议。 – 2012-03-21 03:12:24

+0

@Anteara,请检查我的标题编辑 - 它看起来并不像它正在反映你正在尝试做什么(添加查询参数与发布数据) – 2012-03-21 04:26:51

回答

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? 

它的工作原理,但我不知道这是否是最好的方式来做到这一点。

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

4

您可以使用WebClient Class及其UploadValues methodapplication/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); 
} 
+0

谢谢,我现在可以发布一个常规帖子 - 但是现在我“ m上传一张照片有困难 这就是我所拥有的: http://pastebin.com/kUh5rj2m 这个pastebin也详细介绍了我用来尝试和发布图片我得到一个无法将X转换为我想我可能已经找到了解决方案; 'client.UploadFile' – Anteara 2012-03-21 05:41:05

+0

nope,不要以为我能算出它的意思吗?或者我只是做错了吗? out:/ – Anteara 2012-03-21 05:56:44