2012-08-03 58 views

回答

1

文档提供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

+0

所以我应该读取字符串“responseString”以便找到url吗? – aroshlakshan 2012-08-03 08:54:39

+0

是的,这是正确的。 – 2012-08-03 08:56:17

+0

明白了。我会尝试并让你知道。谢谢 – aroshlakshan 2012-08-03 09:05:17