2012-03-21 212 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