1 year ago

#339844

test-img

EggEgg

c# post request with headers?

I want to post a request to a url, using content-type and authorization. I am getting error 400 "Bad Request". I have tested with the same data and headers in python and it worked.

So I think there is something wrong with how I set up my headers. But I haven't found a workaround.

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http.Headers;
using System.Net.Http;

namespace PostRequests
{

    //var data={"bio":"cheesy"}

    public partial class Form1 : Form
    {
        
        public Form1()
        {
            InitializeComponent();
            
        }
        private static readonly HttpClient client = new HttpClient();

        private void go_Click(object sender, EventArgs e)
        {
            var values = new Dictionary<string, string>
            {
                {"bio", "test"}
            };
            sendPost("https://discord.com/api/v9/users/@me", values);
        }

        async void sendPost(string url, Dictionary<string, string> vals)
        {
            string authValue = "mytoken";

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authValue);
            var content = new FormUrlEncodedContent(vals);
 
            var request = new HttpRequestMessage(new HttpMethod("PATCH"), url) { Content = content };

            request.Headers.Accept.Clear();
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var response = await client.SendAsync(request);
        }
    }
}

c#

http

post

http-patch

0 Answers

Your Answer

Accepted video resources