user11812248
user11812248

Reputation:

How to fix 'The the message received was unexpected or badly formatted'

I've been trying to fix this problem for a while now, but everything I've tried is useless. I tried HttpClientHandler but still getting the error!

Error messages:

SSL connection could not be established, see inner exception

Authentication failed, see inner exception

The the message received was unexpected or badly formatted

[Command("stats")] 
public async Task Profileosu([Remainder]string username = null)
{
    try
    {
        clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };

        HttpClient client = new HttpClient(clientHandler,disposeHandler: true);
        List<Player> player = new List<Player>();
        List<string> lines = File.ReadAllLines(path, encoding: Encoding.UTF8).ToList();
        string id = "";
        foreach (var line in lines)
        {
            string[] readed = line.Split(",");

            Player newPlayer = new Player();
            newPlayer.id = readed[0];
            newPlayer.osuname = readed[1];

            player.Add(newPlayer);
        }

        if (username is null)
        {
            id = Context.User.Id.ToString();
            username = Context.User.Username;
        }
        else if (Context.Message.MentionedUsers.Count > 0)
        {
            username = Context.Message.MentionedUsers.First().Username;
            id = Context.Message.MentionedUsers.First().Id.ToString();
        }
        for (int i = 0; i < player.Count(); i++)
        {
            if (player[i].id == id)
            {
                username = player[i].osuname;
            }
        }

        string url = $"https://osu.ppy.sh/api/get_user?k={k}&u={username}";
        string osuProf = await client.GetStringAsync(url);
        dynamic osuProfile = JsonConvert.DeserializeObject<dynamic>(value: osuProf);
        string pp_raw = osuProfile[0]["pp_raw"];
        string country = osuProfile[0]["country"];
        string user_id = osuProfile[0]["user_id"];
        string joinDate = osuProfile[0]["join_date"];
        string rank = osuProfile[0]["pp_rank"];
        string countryRank = osuProfile[0]["pp_country_rank"];
        string accuracy = osuProfile[0]["accuracy"];
        string playcount = osuProfile[0]["playcount"];
        string userName = osuProfile[0]["username"];



        embed.WithThumbnailUrl($"https://a.ppy.sh/{user_id}");
        embed.WithAuthor($"{username} #{rank}, {pp_raw}PP", Context.Guild.CurrentUser.GetAvatarUrl(), $"https://osu.ppy.sh/users/{user_id}");
        embed.WithDescription($"Join date:{joinDate}\nCountry:{country} #{countryRank}\n");
        embed.WithFooter($"Accuray:{double.Parse(accuracy):F2}%\t\tPlaycount:{playcount}");
        embed.WithColor(154, 255, 0);

        await ReplyAsync($"", false, embed.Build());
    }
    catch (Exception ex)
    {
        embed.WithAuthor("An error occurred");
        embed.WithDescription("This player doesn't exist! Please check the username and try again!");
        embed.WithColor(255, 0, 0);
        await ReplyAsync($"", false, embed.Build());
        Console.WriteLine(ex.Message);
        if (ex.InnerException != null)
        {
            Console.WriteLine(ex.InnerException.Message);
        }
        if (ex.InnerException.InnerException.Message != null)
        {
            Console.WriteLine(ex.InnerException.InnerException.Message);
        }    
    }
}

I learning c# from scratch and I am very beginner in the language so please explain what's the problem.

Upvotes: 2

Views: 10177

Answers (1)

MX D
MX D

Reputation: 2485

This is most likely happening due to the clientHandler you define and use.

For communication with the OSU API you would not really need this either. So instead, you could go ahead and let the HttpClient handle this for you.

So instead of:

clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };

HttpClient client = new HttpClient(clientHandler,disposeHandler: true);

You can define the HttpClient as follows:

HttpClient client = new HttpClient();

As you now no longer define the disposeHandler, it would be a good practice to either add a Finally to your try catch.

Or by applying a using to the HttpClient.

using (var client = new HttpClient())
{
    string url = $"https://osu.ppy.sh/api/get_user?k={Key}&u=d3ullist";
    string osuProf = await client.GetStringAsync(url);
    dynamic osuProfile = JsonConvert.DeserializeObject<dynamic>(value: osuProf);
}

Which will end up with the dynamic object as you where previously expecting it.

enter image description here

Upvotes: 0

Related Questions