2
我想使用API作爲annonymouse用戶將圖片上傳到Imgur.com。在我上傳圖片後,我想動態地獲取圖片網址。我怎樣才能實現這一點使用C#Winforms的?動態獲取已上傳圖片的網址
我想使用API作爲annonymouse用戶將圖片上傳到Imgur.com。在我上傳圖片後,我想動態地獲取圖片網址。我怎樣才能實現這一點使用C#Winforms的?動態獲取已上傳圖片的網址
文檔提供an example,你可以嘗試:
using System;
using System.IO;
using System.Net;
using System.Text;
namespace ImgurExample
{
class Program
{
static void Main(string[] args)
{
PostToImgur(@"C:\Users\ashwin\Desktop\image.jpg", IMGUR_ANONYMOUS_API_KEY);
}
public static void PostToImgur(string imagFilePath, string apiKey)
{
byte[] imageData;
FileStream fileStream = File.OpenRead(imagFilePath);
imageData = new byte[fileStream.Length];
fileStream.Read(imageData, 0, imageData.Length);
fileStream.Close();
const int MAX_URI_LENGTH = 32766;
string base64img = System.Convert.ToBase64String(imageData);
StringBuilder sb = new StringBuilder();
for(int i = 0; i < base64img.Length; i += MAX_URI_LENGTH) {
sb.Append(Uri.EscapeDataString(base64img.Substring(i, Math.Min(MAX_URI_LENGTH, base64img.Length - i))));
}
string uploadRequestString = "image=" + sb.ToString() + "&key=" + imgurApiKey;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://api.imgur.com/2/upload");
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ServicePoint.Expect100Continue = false;
StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream());
streamWriter.Write(uploadRequestString);
streamWriter.Close();
WebResponse response = webRequest.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(responseStream);
string responseString = responseReader.ReadToEnd();
}
}
}
服務器返回的將包含鏈接到上傳圖片的反應。例如:
{
"upload": {
"image": {
"name": false,
"title": "",
"caption": "",
"hash": "cSNjk",
"deletehash": "ZnKGru1reZKoabU",
"datetime": "2010-08-16 22:43:22",
"type": "image\/jpeg",
"animated": "false",
"width": 720,
"height": 540,
"size": 46174,
"views": 0,
"bandwidth": 0
},
"links": {
"original": "http:\/\/imgur.com\/cSNjk.jpg",
"imgur_page": "http:\/\/imgur.com\/cSNjk",
"delete_page": "http:\/\/imgur.com\/delete\/ZnKGru1reZKoabU",
"small_square": "http:\/\/imgur.com\/cSNjks.jpg",
"large_thumbnail": "http:\/\/imgur.com\/cSNjkl.jpg"
}
}
}
要使用匿名API,您需要登錄obtain an API key。
所以我應該讀取字符串「responseString」以便找到url嗎? – aroshlakshan 2012-08-03 08:54:39
是的,這是正確的。 – 2012-08-03 08:56:17
明白了。我會嘗試並讓你知道。謝謝 – aroshlakshan 2012-08-03 09:05:17