How to pass header and Body value using HttpWebRequest in C#?

巧了我就是萌 提交于 2020-12-13 11:01:50

问题


Im trying to POST API credentials data to API through HttpWebRequest class in C#, like i have to pass "Content-Type:application/x-www-form-urlencoded" in Header, then have to pass "grant_type:client_credentials,client_id:ruban123,client_secret:123456" in Body to get response/token (as described in API reference).

Bellow i attached work which i did

    public class DataModel
    {
        public string grant_type { get; set; }
        public string client_id { get; set; }
        public string client_secret { get; set; }
    }
    static void Main(string[] args)
    {

        try
        {
            DataModel dm = new DataModel();
            dm.grant_type = "client_credentials";
            dm.client_id = "ruban123";
            dm.client_secret = "123456";

            var credentials = dm.grant_type + dm.client_id + dm.client_secret;

            #region Http Post
            string messageUri = "https://sampleurl.apivision.com:8493/abc/oauth/token";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(messageUri);
            request.Headers.Add("Authorization", "Basic " + credentials);
            request.ContentType = "application/json";
            request.Method = "POST";
            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                string jsonModel = Newtonsoft.Json.JsonConvert.SerializeObject(dm);
                streamWriter.Write(jsonModel);
                streamWriter.Flush();
                streamWriter.Close();
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            Stream responseStream = response.GetResponseStream();

            string jsonString = null;

            using (StreamReader reader = new StreamReader(responseStream))
            {
                jsonString = reader.ReadToEnd();
                Console.WriteLine();
                reader.Close();
            }

            #endregion Http Post
        }

        catch (Exception ex)
        {
        }
    }[API REFERENCE][1]

回答1:


Here is correct HttpWebRequest using:

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(pathapi);
    request.Method = "POST";
    string postData = "grant_type=client_credentials&client_id=ruban123&client_secret=123456";
    ASCIIEncoding encoding = new ASCIIEncoding();
    byte[] bytes = encoding.GetBytes(postData);

    request.ContentType = "application/x-www-form-urlencoded";

    request.ContentLength = bytes.Length;
    Stream newStream = request.GetRequestStream();
    newStream.Write(bytes, 0, bytes.Length);

    HttpWebResponse response = request.GetResponse() as HttpWebResponse;

HttpWebRequest approach is not relevant. Look at this question Setting Authorization Header of HttpClient




回答2:


It looks like you missed setting of ContentLength property of HttpWebRequest. It should be equal number of bytes to send.

Se this link for more information:

https://docs.microsoft.com/en-us/dotnet/api/system.net.httpwebrequest.contentlength?view=netframework-4.8



来源:https://stackoverflow.com/questions/56253696/how-to-pass-header-and-body-value-using-httpwebrequest-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!