Imgur error 400 Client.uploadString

580 Views Asked by At

I've a pretty long code to upload to imgur, tried to test it out, got some bugs, fixed them. (Also by the help of this site ofc. ) But now I get an error 400.

This is a part of the code, also where it is happening

public static ImgurToken GetToken(string clientId, string clientSecret, string pin)
        {
            string Url = "https://api.imgur.com/oauth2/token/";
            string DataTemplate = "client_id={0}&client_secret={1}&grant_type=pin&pin={2}";
            string Data = String.Format(DataTemplate, clientId, clientSecret, pin);

            using (WebClient Client = new WebClient())
            {
                string ApiResponse = Client.UploadString(Url, Data); //Error 400
                var Deserializer = new JavaScriptSerializer();
                var Response = Deserializer.DeserializeObject(ApiResponse) as Dictionary<string, object>;

                return new ImgurToken()
                {
                    AccessToken = Convert.ToString(Response["access_token"]),
                    RefreshToken = Convert.ToString(Response["refresh_token"])
                };
            }
        }

I think I did the DATA and URL right? It's also states it there on the Imgur API website.

EDIT: Just noticed, my pin is empty. Is this right?
EDIT 2: I checked a little, my ClientSecret is displayed with a red text, but I'm sure it's correct.

GetPin:

public static string GetPin(string clientId, string clientSecret)
        {
            string Pin = String.Empty;
            string OAuthUrlTemplate = "https://api.imgur.com/oauth2/authorize?client_id={0}&response_type={1}&state={2}";
            string RequestUrl = String.Format(OAuthUrlTemplate, clientId, "pin", "blah");
            return Pin;
        }
1

There are 1 best solutions below

5
On

In the imgur documentation, the url doesn't have the trailing /. Change it to https://api.imgur.com/oauth2/token just to be sure.

Additionally, you might have to url encode the Data string. You can use System.Web.HttpUtility.UrlEncode() to do that.

The http 400 error is typically returned when the request has bad syntax, probably your missing pin. Just make sure that the pin you get from the user is added to the Data string and not null or empty.