Question

I'm making a snipping tool that can quickly upload to imgur. But when I'm uploading the image, it gives me a 401 error.

Picture_Viewer.cs

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Web;
using System.Web.Extensions;
using System.Web.Script;
using System.Web.Script.Serialization;
using System.Net;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace Snipping_Tool
{
    public partial class Picture_Viewer : Form
    {


    public Picture_Viewer()
    {
        InitializeComponent();
    }

    int selectX;
    int selectY;
    int selectWidth;
    int selectHeight;
    public Pen selectPen;
    bool start = false;

    const string ClientId = "client_id";
    const string ClientSecret = "client_secret"; //I have it registered but I don't want to show it. Sorry!



    private void Picture_Viewer_MouseMove(object sender, MouseEventArgs e)
    {
        if (pictureBox1.Image == null)
            return;
        //validate if right-click was trigger
        if (start)
        {
            //refresh picture box
            pictureBox1.Refresh();
            //set corner square to mouse coordinates
            selectWidth = e.X - selectX;
            selectHeight = e.Y - selectY;
            //draw dotted rectangle
            pictureBox1.CreateGraphics().DrawRectangle(selectPen,
                      selectX, selectY, selectWidth, selectHeight);
        }
    }

    private void Picture_Viewer_MouseDown(object sender, MouseEventArgs e)
    {
        if (!start)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                //starts coordinates for rectangle
                selectX = e.X;
                selectY = e.Y;
                selectPen = new Pen(Color.Red, 1);
                selectPen.DashStyle = DashStyle.DashDotDot;
            }
            //refresh picture box
            pictureBox1.Refresh();
            //start control variable for draw rectangle
            start = true;
        }
        else
        {
            //validate if there is image
            if (pictureBox1.Image == null)
                return;
            //same functionality when mouse is over
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                pictureBox1.Refresh();
                selectWidth = e.X - selectX;
                selectHeight = e.Y - selectY;
                pictureBox1.CreateGraphics().DrawRectangle(selectPen, selectX,
                         selectY, selectWidth, selectHeight);

            }
            start = false;
            //function save image to clipboard
        }
    }



    private void SaveToClipboard()
    {
        //validate if something selected
        if (selectWidth > 0)
        {

            Rectangle rect = new Rectangle(selectX, selectY, selectWidth, selectHeight);
            //create bitmap with original dimensions
            Bitmap OriginalImage = new Bitmap(pictureBox1.Image, pictureBox1.Width, pictureBox1.Height);
            //create bitmap with selected dimensions
            Bitmap _img = new Bitmap(selectWidth, selectHeight);
            //create graphic variable
            Graphics g = Graphics.FromImage(_img);
            //set graphic attributes
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.DrawImage(OriginalImage, 0, 0, rect, GraphicsUnit.Pixel);
            //insert image stream into clipboard
            Clipboard.SetImage(_img);
        }
        else
        {
            Rectangle rect = new Rectangle(0, 0, pictureBox1.Image.Width, pictureBox1.Image.Height);
            Bitmap OriginalImage = new Bitmap(pictureBox1.Image, pictureBox1.Width, pictureBox1.Height);
            //create bitmap with selected dimensions
            Bitmap _img = new Bitmap(pictureBox1.Image.Width, pictureBox1.Image.Height);
            //create graphic variable
            Graphics g = Graphics.FromImage(_img);
            //set graphic attributes
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.DrawImage(OriginalImage, 0, 0, rect, GraphicsUnit.Pixel);
            Clipboard.SetImage(_img);
        }
        this.Close();
    }

    private void exitToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }

    private void Picture_Viewer_Load(object sender, EventArgs e)
    {

    }

    private void copyToClipboardCTRLCToolStripMenuItem_Click(object sender, EventArgs e)
    {

        SaveToClipboard();
    }

    public Bitmap _img;
    private void uploadToImgurToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (selectWidth > 0)
        {

            Rectangle rect = new Rectangle(selectX, selectY, selectWidth, selectHeight);
            //create bitmap with original dimensions
            Bitmap OriginalImage = new Bitmap(pictureBox1.Image, pictureBox1.Width, pictureBox1.Height);
            //create bitmap with selected dimensions
            Bitmap _img = new Bitmap(selectWidth, selectHeight);
            //create graphic variable
            Graphics g = Graphics.FromImage(_img);
            //set graphic attributes
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.DrawImage(OriginalImage, 0, 0, rect, GraphicsUnit.Pixel);
            //insert image stream into clipboard
            _img.Save(@"C:\Users\Public\Documents\snap.png", ImageFormat.Png);
        }
        else
        {
            Rectangle rect = new Rectangle(0, 0, pictureBox1.Image.Width, pictureBox1.Image.Height);
            Bitmap OriginalImage = new Bitmap(pictureBox1.Image, pictureBox1.Width, pictureBox1.Height);
            //create bitmap with selected dimensions
            Bitmap _img = new Bitmap(pictureBox1.Image.Width, pictureBox1.Image.Height);
            //create graphic variable
            Graphics g = Graphics.FromImage(_img);
            //set graphic attributes
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.DrawImage(OriginalImage, 0, 0, rect, GraphicsUnit.Pixel);
            _img.Save(@"C:\Users\Public\Documents\snap.png", ImageFormat.Png);
        }

        PostToImgur(@"C:\Users\Public\Documents\snap.png", ClientId, ClientSecret);

    }

    public void PostToImgur(string imagFilePath, string apiKey, string apiSecret)
    {
        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 = "client_id" + apiKey + "client_secret" + apiSecret + "&title=" + "imageTitle" +
            "&caption=" + "img" + "&image=" + sb.ToString();

        // strin

        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://api.imgur.com/3/upload.json");
        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(); //401 ERROR
        Stream responseStream = response.GetResponseStream();
        StreamReader responseReader = new StreamReader(responseStream);

        string responseString = responseReader.ReadToEnd();
        this.Close();
    }

}

}

It includes other codes though so it won't work when you try to test it. The error is not in that code, it's really in this. I have the application registered with the API, I have read some Documentary but no where stands where the problem really is. Not even on Google or here.. Thanks in advance :).

EDIT:

Did something with Fiddler but I have no idea how to use it. Here is what the api send (in raw):

CONNECT api.imgur.com:443 HTTP/1.1
Host: api.imgur.com
Connection: Keep-Alive

A SSLv3-compatible ClientHello handshake was found. Fiddler extracted the parameters below.

Version: 3.1 (TLS/1.0)
Random: 52 A8 84 03 80 45 BC AC 57 7A 4B B9 19 88 79 8B 94 A5 43 8A F8 0F 51 4B 07 E1 F8 11 96 33 E1 55
SessionID: empty
Extensions: 
    renegotiation_info  00
    server_name api.imgur.com
    elliptic_curves secp256r1 [0x17], secp384r1 [0x18]
    ec_point_formats    uncompressed [0x0]
    SessionTicket TLS   empty
Ciphers: 
    [002F]  TLS_RSA_AES_128_SHA
    [0035]  TLS_RSA_AES_256_SHA
    [0005]  SSL_RSA_WITH_RC4_128_SHA
    [000A]  SSL_RSA_WITH_3DES_EDE_SHA
    [C013]  TLS1_CK_ECDHE_RSA_WITH_AES_128_CBC_SHA
    [C014]  TLS1_CK_ECDHE_RSA_WITH_AES_256_CBC_SHA
    [C009]  TLS1_CK_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
    [C00A]  TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
    [0032]  TLS_DHE_DSS_WITH_AES_128_SHA
    [0038]  TLS_DHE_DSS_WITH_AES_256_SHA
    [0013]  SSL_DHE_DSS_WITH_3DES_EDE_SHA
    [0004]  SSL_RSA_WITH_RC4_128_MD5

Compression: 
    [00]    NO_COMPRESSION
Was it helpful?

Solution

Looking at the imgur API docs, and your code, it would appear you are not sending a required header: Authorization: Bearer YOUR_ACCESS_TOKEN. Without this token, your request will be 401.

Finally, after obtaining your access_token, you make your API requests by sending the Authorization header as such:

Authorization: Bearer YOUR_ACCESS_TOKEN

Source: https://api.imgur.com/oauth2

Edit as per your comment: to set the auth header in C#, simply add the following line of code when you are preparing your httpwebrequest:

request.Headers['Authorization'] = 'Bearer ' + YOUR_ACCESS_TOKEN;

OTHER TIPS

Without Fiddler logs it's really guessing, so here goes:

"client_id" + apiKey + "client_secret" + apiSecret + "&title=" + "imageTitle" ...

Looks like you're missing two '='s and one '&'. Try:

"client_id=" + apiKey + "&client_secret=" + apiSecret + "&title=" + "imageTitle" ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top